{"version":3,"file":"bundle.mjs","sources":["../node_modules/tslib/tslib.es6.js","../node_modules/@lit/reactive-element/decorators/custom-element.js","../node_modules/@lit/reactive-element/decorators/property.js","../node_modules/@lit/reactive-element/decorators/state.js","../node_modules/@lit/reactive-element/decorators/base.js","../node_modules/@lit/reactive-element/decorators/query.js","../node_modules/@lit/reactive-element/decorators/query-assigned-elements.js","../node_modules/@lit/reactive-element/css-tag.js","../node_modules/@lit/reactive-element/reactive-element.js","../node_modules/lit-html/lit-html.js","../node_modules/lit-element/lit-element.js","../node_modules/@material/web/elevation/internal/elevation.js","../node_modules/@material/web/elevation/internal/elevation-styles.css.js","../node_modules/@material/web/elevation/elevation.js","../node_modules/@material/web/internal/controller/attachable-controller.js","../node_modules/@material/web/focus/internal/focus-ring.js","../node_modules/@material/web/focus/internal/focus-ring-styles.css.js","../node_modules/@material/web/focus/md-focus-ring.js","../node_modules/lit-html/directive.js","../node_modules/lit-html/directives/class-map.js","../node_modules/@material/web/internal/motion/animation.js","../node_modules/@material/web/ripple/internal/ripple.js","../node_modules/@material/web/ripple/internal/ripple-styles.css.js","../node_modules/@material/web/ripple/ripple.js","../node_modules/lit-html/static.js","../node_modules/@material/web/internal/aria/aria.js","../node_modules/@material/web/internal/aria/delegate.js","../node_modules/@material/web/internal/controller/events.js","../node_modules/@material/web/button/internal/button.js","../node_modules/@material/web/button/internal/filled-button.js","../node_modules/@material/web/button/internal/filled-styles.css.js","../node_modules/@material/web/button/internal/shared-elevation-styles.css.js","../node_modules/@material/web/button/internal/shared-styles.css.js","../node_modules/@material/web/button/filled-button.js","../node_modules/@material/web/button/internal/outlined-button.js","../node_modules/@material/web/button/internal/outlined-styles.css.js","../node_modules/@material/web/button/outlined-button.js","../node_modules/@material/web/button/internal/text-button.js","../node_modules/@material/web/button/internal/text-styles.css.js","../node_modules/@material/web/button/text-button.js","../node_modules/@material/web/checkbox/internal/checkbox.js","../node_modules/@material/web/checkbox/internal/checkbox-styles.css.js","../node_modules/@material/web/checkbox/checkbox.js","../node_modules/@material/web/icon/internal/icon.js","../node_modules/@material/web/icon/internal/icon-styles.css.js","../node_modules/@material/web/icon/icon.js","../node_modules/@material/web/progress/internal/progress.js","../node_modules/@material/web/progress/internal/circular-progress.js","../node_modules/@material/web/progress/internal/circular-progress-styles.css.js","../node_modules/@material/web/progress/circular-progress.js","../node_modules/@material/web/radio/internal/forced-colors-styles.css.js","../node_modules/@material/web/radio/internal/single-selection-controller.js","../node_modules/@material/web/radio/internal/radio.js","../node_modules/@material/web/radio/internal/radio-styles.css.js","../node_modules/@material/web/radio/radio.js","../node_modules/@material/web/field/internal/field.js","../node_modules/@material/web/field/internal/outlined-field.js","../node_modules/@material/web/field/internal/outlined-styles.css.js","../node_modules/@material/web/field/internal/shared-styles.css.js","../node_modules/@material/web/field/outlined-field.js","../node_modules/@material/web/textfield/internal/outlined-forced-colors-styles.css.js","../node_modules/@material/web/textfield/internal/outlined-styles.css.js","../node_modules/lit-html/directive-helpers.js","../node_modules/lit-html/directives/live.js","../node_modules/lit-html/directives/style-map.js","../node_modules/@material/web/internal/controller/string-converter.js","../node_modules/@material/web/textfield/internal/text-field.js","../node_modules/@material/web/textfield/internal/outlined-text-field.js","../node_modules/@material/web/textfield/internal/shared-styles.css.js","../node_modules/@material/web/textfield/outlined-text-field.js","../node_modules/@vaadin/vaadin-lumo-styles/version.js","../node_modules/@vaadin/vaadin-themable-mixin/vaadin-theme-property-mixin.js","../node_modules/@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js","../node_modules/@vaadin/vaadin-lumo-styles/global.js","../node_modules/@vaadin/vaadin-themable-mixin/register-styles.js","../node_modules/@vaadin/vaadin-lumo-styles/color.js","../node_modules/@vaadin/vaadin-lumo-styles/sizing.js","../node_modules/@vaadin/vaadin-lumo-styles/style.js","../node_modules/@vaadin/vaadin-lumo-styles/typography.js","../node_modules/@vaadin/input-container/theme/lumo/vaadin-input-container-styles.js","../node_modules/@polymer/polymer/lib/utils/boot.js","../node_modules/@polymer/polymer/lib/utils/resolve-url.js","../node_modules/@polymer/polymer/lib/utils/settings.js","../node_modules/@polymer/polymer/lib/utils/mixin.js","../node_modules/@polymer/polymer/lib/elements/dom-module.js","../node_modules/@polymer/polymer/lib/utils/style-gather.js","../node_modules/@polymer/polymer/lib/utils/wrap.js","../node_modules/@polymer/polymer/lib/utils/path.js","../node_modules/@polymer/polymer/lib/utils/case-map.js","../node_modules/@polymer/polymer/lib/utils/async.js","../node_modules/@polymer/polymer/lib/mixins/properties-changed.js","../node_modules/@polymer/polymer/lib/mixins/property-accessors.js","../node_modules/@polymer/polymer/lib/mixins/template-stamp.js","../node_modules/@polymer/polymer/lib/mixins/property-effects.js","../node_modules/@polymer/polymer/lib/mixins/properties-mixin.js","../node_modules/@polymer/polymer/lib/mixins/element-mixin.js","../node_modules/@polymer/polymer/lib/utils/html-tag.js","../node_modules/@polymer/polymer/polymer-element.js","../node_modules/@vaadin/component-base/src/dir-mixin.js","../node_modules/@vaadin/input-container/src/vaadin-input-container.js","../node_modules/@vaadin/vaadin-lumo-styles/spacing.js","../node_modules/@vaadin/vaadin-lumo-styles/mixins/overlay.js","../node_modules/@vaadin/overlay/theme/lumo/vaadin-overlay-styles.js","../node_modules/@polymer/polymer/lib/utils/render-status.js","../node_modules/@vaadin/component-base/src/browser-utils.js","../node_modules/@vaadin/component-base/src/templates.js","../node_modules/@vaadin/a11y-base/src/aria-hidden.js","../node_modules/@vaadin/a11y-base/src/aria-modal-controller.js","../node_modules/@vaadin/a11y-base/src/focus-utils.js","../node_modules/@vaadin/a11y-base/src/focus-restoration-controller.js","../node_modules/@vaadin/a11y-base/src/focus-trap-controller.js","../node_modules/@vaadin/component-base/src/controller-mixin.js","../node_modules/@vaadin/overlay/src/vaadin-overlay-focus-mixin.js","../node_modules/@vaadin/overlay/src/vaadin-overlay.js","../node_modules/@vaadin/vaadin-lumo-styles/mixins/menu-overlay.js","../node_modules/@vaadin/date-picker/theme/lumo/vaadin-date-picker-overlay-styles.js","../node_modules/@vaadin/button/theme/lumo/vaadin-button-styles.js","../node_modules/@vaadin/vaadin-development-mode-detector/vaadin-development-mode-detector.js","../node_modules/@vaadin/vaadin-usage-statistics/vaadin-usage-statistics-collect.js","../node_modules/@vaadin/component-base/src/async.js","../node_modules/@vaadin/component-base/src/debounce.js","../node_modules/@vaadin/component-base/src/element-mixin.js","../node_modules/@polymer/polymer/lib/utils/array-splice.js","../node_modules/@polymer/polymer/lib/utils/flattened-nodes-observer.js","../node_modules/@vaadin/component-base/src/dom-utils.js","../node_modules/@vaadin/component-base/src/unique-id-utils.js","../node_modules/@vaadin/component-base/src/slot-controller.js","../node_modules/@vaadin/component-base/src/tooltip-controller.js","../node_modules/@vaadin/button/src/vaadin-button-base.js","../node_modules/@vaadin/component-base/src/gestures.js","../node_modules/@vaadin/a11y-base/src/disabled-mixin.js","../node_modules/@vaadin/a11y-base/src/keyboard-mixin.js","../node_modules/@vaadin/a11y-base/src/active-mixin.js","../node_modules/@vaadin/a11y-base/src/focus-mixin.js","../node_modules/@vaadin/a11y-base/src/tabindex-mixin.js","../node_modules/@vaadin/button/src/vaadin-button-mixin.js","../node_modules/@vaadin/button/src/vaadin-button.js","../node_modules/@vaadin/date-picker/theme/lumo/vaadin-date-picker-year-styles.js","../node_modules/@vaadin/date-picker/theme/lumo/vaadin-date-picker-overlay-content-styles.js","../node_modules/@vaadin/date-picker/theme/lumo/vaadin-month-calendar-styles.js","../node_modules/@vaadin/vaadin-lumo-styles/font-icons.js","../node_modules/@vaadin/vaadin-lumo-styles/mixins/field-button.js","../node_modules/@vaadin/vaadin-lumo-styles/mixins/helper.js","../node_modules/@vaadin/vaadin-lumo-styles/mixins/required-field.js","../node_modules/@vaadin/vaadin-lumo-styles/mixins/input-field-shared.js","../node_modules/@vaadin/date-picker/theme/lumo/vaadin-date-picker-styles.js","../node_modules/@vaadin/overlay/src/vaadin-overlay-position-mixin.js","../node_modules/@vaadin/date-picker/src/vaadin-date-picker-overlay.js","../node_modules/@polymer/polymer/lib/mixins/mutable-data.js","../node_modules/@polymer/polymer/lib/utils/templatize.js","../node_modules/@polymer/polymer/lib/utils/debounce.js","../node_modules/@polymer/polymer/lib/utils/flush.js","../node_modules/@polymer/polymer/lib/utils/hide-template-controls.js","../node_modules/@polymer/polymer/lib/elements/dom-repeat.js","../node_modules/@vaadin/date-picker/src/vaadin-date-picker-helper.js","../node_modules/@vaadin/date-picker/src/vaadin-month-calendar.js","../node_modules/@vaadin/date-picker/src/vaadin-infinite-scroller.js","../node_modules/@vaadin/date-picker/src/vaadin-date-picker-month-scroller.js","../node_modules/@vaadin/date-picker/src/vaadin-date-picker-year-scroller.js","../node_modules/@vaadin/date-picker/src/vaadin-date-picker-year.js","../node_modules/@vaadin/component-base/src/media-query-controller.js","../node_modules/@vaadin/date-picker/src/vaadin-date-picker-overlay-content.js","../node_modules/@vaadin/a11y-base/src/delegate-focus-mixin.js","../node_modules/@vaadin/field-base/src/input-mixin.js","../node_modules/@vaadin/field-base/src/clear-button-mixin.js","../node_modules/@vaadin/a11y-base/src/aria-id-reference.js","../node_modules/@vaadin/a11y-base/src/field-aria-controller.js","../node_modules/@vaadin/component-base/src/slot-child-observe-controller.js","../node_modules/@vaadin/field-base/src/error-controller.js","../node_modules/@vaadin/field-base/src/helper-controller.js","../node_modules/@vaadin/field-base/src/label-controller.js","../node_modules/@vaadin/field-base/src/label-mixin.js","../node_modules/@vaadin/field-base/src/validate-mixin.js","../node_modules/@vaadin/field-base/src/field-mixin.js","../node_modules/@vaadin/component-base/src/delegate-state-mixin.js","../node_modules/@vaadin/field-base/src/input-constraints-mixin.js","../node_modules/@vaadin/field-base/src/slot-styles-mixin.js","../node_modules/@vaadin/field-base/src/input-control-mixin.js","../node_modules/@vaadin/field-base/src/input-controller.js","../node_modules/@vaadin/field-base/src/labelled-input-controller.js","../node_modules/@vaadin/field-base/src/styles/clear-button-styles.js","../node_modules/@vaadin/field-base/src/styles/input-field-shared-styles.js","../node_modules/@vaadin/field-base/src/styles/field-shared-styles.js","../node_modules/@vaadin/field-base/src/styles/input-field-container-styles.js","../node_modules/@vaadin/component-base/src/overlay-class-mixin.js","../node_modules/@vaadin/field-base/src/virtual-keyboard-controller.js","../node_modules/@vaadin/date-picker/src/vaadin-date-picker-mixin.js","../node_modules/@vaadin/date-picker/src/vaadin-date-picker.js","../node_modules/@vaadin/item/theme/lumo/vaadin-item-styles.js","../node_modules/@vaadin/combo-box/theme/lumo/vaadin-combo-box-item-styles.js","../node_modules/@vaadin/vaadin-lumo-styles/mixins/loader.js","../node_modules/@vaadin/combo-box/theme/lumo/vaadin-combo-box-overlay-styles.js","../node_modules/@vaadin/time-picker/theme/lumo/vaadin-time-picker-styles.js","../node_modules/@vaadin/combo-box/src/vaadin-combo-box-item-mixin.js","../node_modules/@vaadin/time-picker/src/vaadin-time-picker-item.js","../node_modules/@vaadin/component-base/src/iron-list-core.js","../node_modules/@vaadin/component-base/src/virtualizer-iron-list-adapter.js","../node_modules/@vaadin/component-base/src/virtualizer.js","../node_modules/@vaadin/combo-box/src/vaadin-combo-box-placeholder.js","../node_modules/@vaadin/combo-box/src/vaadin-combo-box-scroller-mixin.js","../node_modules/@vaadin/time-picker/src/vaadin-time-picker-scroller.js","../node_modules/@vaadin/combo-box/src/vaadin-combo-box-overlay-mixin.js","../node_modules/@vaadin/time-picker/src/vaadin-time-picker-overlay.js","../node_modules/@vaadin/combo-box/src/vaadin-combo-box-mixin.js","../node_modules/@vaadin/time-picker/src/vaadin-time-picker-combo-box.js","../node_modules/@vaadin/field-base/src/pattern-mixin.js","../node_modules/@vaadin/time-picker/src/vaadin-time-picker.js","../node_modules/@vaadin/tooltip/src/vaadin-tooltip-overlay.js","../node_modules/@vaadin/tooltip/theme/lumo/vaadin-tooltip-styles.js","../node_modules/@vaadin/tooltip/src/vaadin-tooltip.js","../node_modules/vanilla-colorful/lib/utils/math.js","../node_modules/vanilla-colorful/lib/utils/convert.js","../node_modules/vanilla-colorful/lib/utils/compare.js","../node_modules/vanilla-colorful/lib/utils/dom.js","../node_modules/vanilla-colorful/lib/components/slider.js","../node_modules/vanilla-colorful/lib/components/hue.js","../node_modules/vanilla-colorful/lib/components/saturation.js","../node_modules/vanilla-colorful/lib/components/color-picker.js","../node_modules/vanilla-colorful/lib/styles/color-picker.js","../node_modules/vanilla-colorful/lib/styles/hue.js","../node_modules/vanilla-colorful/lib/styles/saturation.js","../node_modules/vanilla-colorful/lib/entrypoints/hex.js","../node_modules/vanilla-colorful/hex-color-picker.js","../node_modules/@bugsnag/browser/dist/bugsnag.js","../node_modules/@firebase/util/dist/index.esm2017.js","../node_modules/@vaadin/notification/theme/lumo/vaadin-notification-styles.js","../node_modules/@vaadin/notification/src/vaadin-notification.js","../node_modules/@vaadin/router/dist/vaadin-router.js","../node_modules/@firebase/component/dist/esm/index.esm2017.js","../node_modules/@firebase/logger/dist/esm/index.esm2017.js","../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../node_modules/@firebase/app/dist/esm/index.esm2017.js","../node_modules/@firebase/auth/dist/esm2017/index-e24386e7.js","../node_modules/js-cookie/dist/js.cookie.mjs","../node_modules/@firebase/webchannel-wrapper/dist/esm/index.esm2017.js","../node_modules/@firebase/firestore/dist/index.esm2017.js","../src/util/asserts.ts","../src/firebase/firestore_state.ts","../src/data/collections.ts","../src/data/entity.ts","../src/data/user.ts","../src/firebase/auth_state.ts","../node_modules/firebase/app/dist/esm/index.esm.js","../node_modules/@firebase/functions/dist/index.esm2017.js","../node_modules/luxon/src/errors.js","../node_modules/luxon/src/impl/formats.js","../node_modules/luxon/src/zone.js","../node_modules/luxon/src/zones/systemZone.js","../node_modules/luxon/src/zones/IANAZone.js","../node_modules/luxon/src/impl/locale.js","../node_modules/luxon/src/impl/english.js","../node_modules/luxon/src/zones/fixedOffsetZone.js","../node_modules/luxon/src/zones/invalidZone.js","../node_modules/luxon/src/impl/zoneUtil.js","../node_modules/luxon/src/impl/util.js","../node_modules/luxon/src/settings.js","../node_modules/luxon/src/impl/formatter.js","../node_modules/luxon/src/impl/invalid.js","../node_modules/luxon/src/impl/regexParser.js","../node_modules/luxon/src/duration.js","../node_modules/luxon/src/interval.js","../node_modules/luxon/src/info.js","../node_modules/luxon/src/impl/diff.js","../node_modules/luxon/src/impl/digits.js","../node_modules/luxon/src/impl/tokenParser.js","../node_modules/luxon/src/impl/conversions.js","../node_modules/luxon/src/datetime.js","../src/data/batch.ts","../src/data/invite.ts","../src/firebase/functions_state.ts","../node_modules/@firebase/storage/dist/index.esm2017.js","../src/firebase/storage_state.ts","../src/firebase/firebase_state.ts","../src/elements/base.ts","../src/elements/events.ts","../src/elements/app/index.ts","../src/elements/dialog/index.ts","../src/elements/dialog_action_button/index.ts","../src/elements/dialog_close_button/index.ts","../src/elements/header/index.ts","../src/elements/icon_button/index.ts","../src/elements/login_view/index.ts"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n    extendStatics = Object.setPrototypeOf ||\r\n        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n    return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n    if (typeof b !== \"function\" && b !== null)\r\n        throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n    extendStatics(d, b);\r\n    function __() { this.constructor = d; }\r\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n    __assign = Object.assign || function __assign(t) {\r\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n            s = arguments[i];\r\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n        }\r\n        return t;\r\n    }\r\n    return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n    var t = {};\r\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n        t[p] = s[p];\r\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                t[p[i]] = s[p[i]];\r\n        }\r\n    return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n    return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n    function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n    var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n    var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n    var _, done = false;\r\n    for (var i = decorators.length - 1; i >= 0; i--) {\r\n        var context = {};\r\n        for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n        for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n        context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n        var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n        if (kind === \"accessor\") {\r\n            if (result === void 0) continue;\r\n            if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n            if (_ = accept(result.get)) descriptor.get = _;\r\n            if (_ = accept(result.set)) descriptor.set = _;\r\n            if (_ = accept(result.init)) initializers.unshift(_);\r\n        }\r\n        else if (_ = accept(result)) {\r\n            if (kind === \"field\") initializers.unshift(_);\r\n            else descriptor[key] = _;\r\n        }\r\n    }\r\n    if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n    done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n    var useValue = arguments.length > 2;\r\n    for (var i = 0; i < initializers.length; i++) {\r\n        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n    }\r\n    return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n    return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n    if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n    return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n    if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n    return new (P || (P = Promise))(function (resolve, reject) {\r\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n    });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n    function verb(n) { return function (v) { return step([n, v]); }; }\r\n    function step(op) {\r\n        if (f) throw new TypeError(\"Generator is already executing.\");\r\n        while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n            if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n            if (y = 0, t) op = [op[0] & 2, t.value];\r\n            switch (op[0]) {\r\n                case 0: case 1: t = op; break;\r\n                case 4: _.label++; return { value: op[1], done: false };\r\n                case 5: _.label++; y = op[1]; op = [0]; continue;\r\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n                default:\r\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n                    if (t[2]) _.ops.pop();\r\n                    _.trys.pop(); continue;\r\n            }\r\n            op = body.call(thisArg, _);\r\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n    }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    var desc = Object.getOwnPropertyDescriptor(m, k);\r\n    if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n        desc = { enumerable: true, get: function() { return m[k]; } };\r\n    }\r\n    Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n    var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n    if (m) return m.call(o);\r\n    if (o && typeof o.length === \"number\") return {\r\n        next: function () {\r\n            if (o && i >= o.length) o = void 0;\r\n            return { value: o && o[i++], done: !o };\r\n        }\r\n    };\r\n    throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n    if (!m) return o;\r\n    var i = m.call(o), r, ar = [], e;\r\n    try {\r\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n    }\r\n    catch (error) { e = { error: error }; }\r\n    finally {\r\n        try {\r\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n        }\r\n        finally { if (e) throw e.error; }\r\n    }\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n    for (var ar = [], i = 0; i < arguments.length; i++)\r\n        ar = ar.concat(__read(arguments[i]));\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n    for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n            r[k] = a[j];\r\n    return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n        if (ar || !(i in from)) {\r\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n            ar[i] = from[i];\r\n        }\r\n    }\r\n    return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n    return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n    return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n    function fulfill(value) { resume(\"next\", value); }\r\n    function reject(value) { resume(\"throw\", value); }\r\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n    var i, p;\r\n    return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var m = o[Symbol.asyncIterator], i;\r\n    return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n    if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n    return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n    o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n    if (mod && mod.__esModule) return mod;\r\n    var result = {};\r\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n    __setModuleDefault(result, mod);\r\n    return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n    return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n    if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n    return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n    if (value !== null && value !== void 0) {\r\n        if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n        var dispose;\r\n        if (async) {\r\n            if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n            dispose = value[Symbol.asyncDispose];\r\n        }\r\n        if (dispose === void 0) {\r\n            if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n            dispose = value[Symbol.dispose];\r\n        }\r\n        if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n        env.stack.push({ value: value, dispose: dispose, async: async });\r\n    }\r\n    else if (async) {\r\n        env.stack.push({ async: true });\r\n    }\r\n    return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n    var e = new Error(message);\r\n    return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n    function fail(e) {\r\n        env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n        env.hasError = true;\r\n    }\r\n    function next() {\r\n        while (env.stack.length) {\r\n            var rec = env.stack.pop();\r\n            try {\r\n                var result = rec.dispose && rec.dispose.call(rec.value);\r\n                if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n            }\r\n            catch (e) {\r\n                fail(e);\r\n            }\r\n        }\r\n        if (env.hasError) throw env.error;\r\n    }\r\n    return next();\r\n}\r\n\r\nexport default {\r\n    __extends: __extends,\r\n    __assign: __assign,\r\n    __rest: __rest,\r\n    __decorate: __decorate,\r\n    __param: __param,\r\n    __metadata: __metadata,\r\n    __awaiter: __awaiter,\r\n    __generator: __generator,\r\n    __createBinding: __createBinding,\r\n    __exportStar: __exportStar,\r\n    __values: __values,\r\n    __read: __read,\r\n    __spread: __spread,\r\n    __spreadArrays: __spreadArrays,\r\n    __spreadArray: __spreadArray,\r\n    __await: __await,\r\n    __asyncGenerator: __asyncGenerator,\r\n    __asyncDelegator: __asyncDelegator,\r\n    __asyncValues: __asyncValues,\r\n    __makeTemplateObject: __makeTemplateObject,\r\n    __importStar: __importStar,\r\n    __importDefault: __importDefault,\r\n    __classPrivateFieldGet: __classPrivateFieldGet,\r\n    __classPrivateFieldSet: __classPrivateFieldSet,\r\n    __classPrivateFieldIn: __classPrivateFieldIn,\r\n    __addDisposableResource: __addDisposableResource,\r\n    __disposeResources: __disposeResources,\r\n};\r\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst e=e=>n=>\"function\"==typeof n?((e,n)=>(customElements.define(e,n),n))(e,n):((e,n)=>{const{kind:t,elements:s}=n;return{kind:t,elements:s,finisher(n){customElements.define(e,n)}}})(e,n);export{e as customElement};\n//# sourceMappingURL=custom-element.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst i=(i,e)=>\"method\"===e.kind&&e.descriptor&&!(\"value\"in e.descriptor)?{...e,finisher(n){n.createProperty(e.key,i)}}:{kind:\"field\",key:Symbol(),placement:\"own\",descriptor:{},originalKey:e.key,initializer(){\"function\"==typeof e.initializer&&(this[e.key]=e.initializer.call(this))},finisher(n){n.createProperty(e.key,i)}},e=(i,e,n)=>{e.constructor.createProperty(n,i)};function n(n){return(t,o)=>void 0!==o?e(n,t,o):i(n,t)}export{n as property};\n//# sourceMappingURL=property.js.map\n","import{property as r}from\"./property.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */function t(t){return r({...t,state:!0})}export{t as state};\n//# sourceMappingURL=state.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst e=(e,t,o)=>{Object.defineProperty(t,o,e)},t=(e,t)=>({kind:\"method\",placement:\"prototype\",key:t.key,descriptor:e}),o=({finisher:e,descriptor:t})=>(o,n)=>{var r;if(void 0===n){const n=null!==(r=o.originalKey)&&void 0!==r?r:o.key,i=null!=t?{kind:\"method\",placement:\"prototype\",key:n,descriptor:t(o.key)}:{...o,key:n};return null!=e&&(i.finisher=function(t){e(t,n)}),i}{const r=o.constructor;void 0!==t&&Object.defineProperty(o,n,t(n)),null==e||e(r,n)}};export{o as decorateProperty,e as legacyPrototypeMethod,t as standardPrototypeMethod};\n//# sourceMappingURL=base.js.map\n","import{decorateProperty as o}from\"./base.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */function i(i,n){return o({descriptor:o=>{const t={get(){var o,n;return null!==(n=null===(o=this.renderRoot)||void 0===o?void 0:o.querySelector(i))&&void 0!==n?n:null},enumerable:!0,configurable:!0};if(n){const n=\"symbol\"==typeof o?Symbol():\"__\"+o;t.get=function(){var o,t;return void 0===this[n]&&(this[n]=null!==(t=null===(o=this.renderRoot)||void 0===o?void 0:o.querySelector(i))&&void 0!==t?t:null),this[n]}}return t}})}export{i as query};\n//# sourceMappingURL=query.js.map\n","import{decorateProperty as o}from\"./base.js\";\n/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */var n;const e=null!=(null===(n=window.HTMLSlotElement)||void 0===n?void 0:n.prototype.assignedElements)?(o,n)=>o.assignedElements(n):(o,n)=>o.assignedNodes(n).filter((o=>o.nodeType===Node.ELEMENT_NODE));function l(n){const{slot:l,selector:t}=null!=n?n:{};return o({descriptor:o=>({get(){var o;const r=\"slot\"+(l?`[name=${l}]`:\":not([name])\"),i=null===(o=this.renderRoot)||void 0===o?void 0:o.querySelector(r),s=null!=i?e(i,n):[];return t?s.filter((o=>o.matches(t))):s},enumerable:!0,configurable:!0})})}export{l as queryAssignedElements};\n//# sourceMappingURL=query-assigned-elements.js.map\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=window,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&\"adoptedStyleSheets\"in Document.prototype&&\"replace\"in CSSStyleSheet.prototype,s=Symbol(),n=new WeakMap;class o{constructor(t,e,n){if(this._$cssResult$=!0,n!==s)throw Error(\"CSSResult is not constructable. Use `unsafeCSS` or `css` instead.\");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const s=this.t;if(e&&void 0===t){const e=void 0!==s&&1===s.length;e&&(t=n.get(s)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&n.set(s,t))}return t}toString(){return this.cssText}}const r=t=>new o(\"string\"==typeof t?t:t+\"\",void 0,s),i=(t,...e)=>{const n=1===t.length?t[0]:e.reduce(((e,s,n)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if(\"number\"==typeof t)return t;throw Error(\"Value passed to 'css' function must be a 'css' function result: \"+t+\". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.\")})(s)+t[n+1]),t[0]);return new o(n,t,s)},S=(s,n)=>{e?s.adoptedStyleSheets=n.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet)):n.forEach((e=>{const n=document.createElement(\"style\"),o=t.litNonce;void 0!==o&&n.setAttribute(\"nonce\",o),n.textContent=e.cssText,s.appendChild(n)}))},c=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e=\"\";for(const s of t.cssRules)e+=s.cssText;return r(e)})(t):t;export{o as CSSResult,S as adoptStyles,i as css,c as getCompatibleStyle,e as supportsAdoptingStyleSheets,r as unsafeCSS};\n//# sourceMappingURL=css-tag.js.map\n","import{getCompatibleStyle as t,adoptStyles as i}from\"./css-tag.js\";export{CSSResult,adoptStyles,css,getCompatibleStyle,supportsAdoptingStyleSheets,unsafeCSS}from\"./css-tag.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */var s;const e=window,r=e.trustedTypes,h=r?r.emptyScript:\"\",o=e.reactiveElementPolyfillSupport,n={toAttribute(t,i){switch(i){case Boolean:t=t?h:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,i){let s=t;switch(i){case Boolean:s=null!==t;break;case Number:s=null===t?null:Number(t);break;case Object:case Array:try{s=JSON.parse(t)}catch(t){s=null}}return s}},a=(t,i)=>i!==t&&(i==i||t==t),l={attribute:!0,type:String,converter:n,reflect:!1,hasChanged:a},d=\"finalized\";class u extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this.u()}static addInitializer(t){var i;this.finalize(),(null!==(i=this.h)&&void 0!==i?i:this.h=[]).push(t)}static get observedAttributes(){this.finalize();const t=[];return this.elementProperties.forEach(((i,s)=>{const e=this._$Ep(s,i);void 0!==e&&(this._$Ev.set(e,s),t.push(e))})),t}static createProperty(t,i=l){if(i.state&&(i.attribute=!1),this.finalize(),this.elementProperties.set(t,i),!i.noAccessor&&!this.prototype.hasOwnProperty(t)){const s=\"symbol\"==typeof t?Symbol():\"__\"+t,e=this.getPropertyDescriptor(t,s,i);void 0!==e&&Object.defineProperty(this.prototype,t,e)}}static getPropertyDescriptor(t,i,s){return{get(){return this[i]},set(e){const r=this[t];this[i]=e,this.requestUpdate(t,r,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)||l}static finalize(){if(this.hasOwnProperty(d))return!1;this[d]=!0;const t=Object.getPrototypeOf(this);if(t.finalize(),void 0!==t.h&&(this.h=[...t.h]),this.elementProperties=new Map(t.elementProperties),this._$Ev=new Map,this.hasOwnProperty(\"properties\")){const t=this.properties,i=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const s of i)this.createProperty(s,t[s])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(i){const s=[];if(Array.isArray(i)){const e=new Set(i.flat(1/0).reverse());for(const i of e)s.unshift(t(i))}else void 0!==i&&s.push(t(i));return s}static _$Ep(t,i){const s=i.attribute;return!1===s?void 0:\"string\"==typeof s?s:\"string\"==typeof t?t.toLowerCase():void 0}u(){var t;this._$E_=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$Eg(),this.requestUpdate(),null===(t=this.constructor.h)||void 0===t||t.forEach((t=>t(this)))}addController(t){var i,s;(null!==(i=this._$ES)&&void 0!==i?i:this._$ES=[]).push(t),void 0!==this.renderRoot&&this.isConnected&&(null===(s=t.hostConnected)||void 0===s||s.call(t))}removeController(t){var i;null===(i=this._$ES)||void 0===i||i.splice(this._$ES.indexOf(t)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach(((t,i)=>{this.hasOwnProperty(i)&&(this._$Ei.set(i,this[i]),delete this[i])}))}createRenderRoot(){var t;const s=null!==(t=this.shadowRoot)&&void 0!==t?t:this.attachShadow(this.constructor.shadowRootOptions);return i(s,this.constructor.elementStyles),s}connectedCallback(){var t;void 0===this.renderRoot&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),null===(t=this._$ES)||void 0===t||t.forEach((t=>{var i;return null===(i=t.hostConnected)||void 0===i?void 0:i.call(t)}))}enableUpdating(t){}disconnectedCallback(){var t;null===(t=this._$ES)||void 0===t||t.forEach((t=>{var i;return null===(i=t.hostDisconnected)||void 0===i?void 0:i.call(t)}))}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$EO(t,i,s=l){var e;const r=this.constructor._$Ep(t,s);if(void 0!==r&&!0===s.reflect){const h=(void 0!==(null===(e=s.converter)||void 0===e?void 0:e.toAttribute)?s.converter:n).toAttribute(i,s.type);this._$El=t,null==h?this.removeAttribute(r):this.setAttribute(r,h),this._$El=null}}_$AK(t,i){var s;const e=this.constructor,r=e._$Ev.get(t);if(void 0!==r&&this._$El!==r){const t=e.getPropertyOptions(r),h=\"function\"==typeof t.converter?{fromAttribute:t.converter}:void 0!==(null===(s=t.converter)||void 0===s?void 0:s.fromAttribute)?t.converter:n;this._$El=r,this[r]=h.fromAttribute(i,t.type),this._$El=null}}requestUpdate(t,i,s){let e=!0;void 0!==t&&(((s=s||this.constructor.getPropertyOptions(t)).hasChanged||a)(this[t],i)?(this._$AL.has(t)||this._$AL.set(t,i),!0===s.reflect&&this._$El!==t&&(void 0===this._$EC&&(this._$EC=new Map),this._$EC.set(t,s))):e=!1),!this.isUpdatePending&&e&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var t;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach(((t,i)=>this[i]=t)),this._$Ei=void 0);let i=!1;const s=this._$AL;try{i=this.shouldUpdate(s),i?(this.willUpdate(s),null===(t=this._$ES)||void 0===t||t.forEach((t=>{var i;return null===(i=t.hostUpdate)||void 0===i?void 0:i.call(t)})),this.update(s)):this._$Ek()}catch(t){throw i=!1,this._$Ek(),t}i&&this._$AE(s)}willUpdate(t){}_$AE(t){var i;null===(i=this._$ES)||void 0===i||i.forEach((t=>{var i;return null===(i=t.hostUpdated)||void 0===i?void 0:i.call(t)})),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(t){return!0}update(t){void 0!==this._$EC&&(this._$EC.forEach(((t,i)=>this._$EO(i,this[i],t))),this._$EC=void 0),this._$Ek()}updated(t){}firstUpdated(t){}}u[d]=!0,u.elementProperties=new Map,u.elementStyles=[],u.shadowRootOptions={mode:\"open\"},null==o||o({ReactiveElement:u}),(null!==(s=e.reactiveElementVersions)&&void 0!==s?s:e.reactiveElementVersions=[]).push(\"1.6.2\");export{u as ReactiveElement,n as defaultConverter,a as notEqual};\n//# sourceMappingURL=reactive-element.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nvar t;const i=window,s=i.trustedTypes,e=s?s.createPolicy(\"lit-html\",{createHTML:t=>t}):void 0,o=\"$lit$\",n=`lit$${(Math.random()+\"\").slice(9)}$`,l=\"?\"+n,h=`<${l}>`,r=document,u=()=>r.createComment(\"\"),d=t=>null===t||\"object\"!=typeof t&&\"function\"!=typeof t,c=Array.isArray,v=t=>c(t)||\"function\"==typeof(null==t?void 0:t[Symbol.iterator]),a=\"[ \\t\\n\\f\\r]\",f=/<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g,_=/-->/g,m=/>/g,p=RegExp(`>|${a}(?:([^\\\\s\"'>=/]+)(${a}*=${a}*(?:[^ \\t\\n\\f\\r\"'\\`<>=]|(\"|')|))|$)`,\"g\"),g=/'/g,$=/\"/g,y=/^(?:script|style|textarea|title)$/i,w=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),x=w(1),b=w(2),T=Symbol.for(\"lit-noChange\"),A=Symbol.for(\"lit-nothing\"),E=new WeakMap,C=r.createTreeWalker(r,129,null,!1);function P(t,i){if(!Array.isArray(t)||!t.hasOwnProperty(\"raw\"))throw Error(\"invalid template strings array\");return void 0!==e?e.createHTML(i):i}const V=(t,i)=>{const s=t.length-1,e=[];let l,r=2===i?\"<svg>\":\"\",u=f;for(let i=0;i<s;i++){const s=t[i];let d,c,v=-1,a=0;for(;a<s.length&&(u.lastIndex=a,c=u.exec(s),null!==c);)a=u.lastIndex,u===f?\"!--\"===c[1]?u=_:void 0!==c[1]?u=m:void 0!==c[2]?(y.test(c[2])&&(l=RegExp(\"</\"+c[2],\"g\")),u=p):void 0!==c[3]&&(u=p):u===p?\">\"===c[0]?(u=null!=l?l:f,v=-1):void 0===c[1]?v=-2:(v=u.lastIndex-c[2].length,d=c[1],u=void 0===c[3]?p:'\"'===c[3]?$:g):u===$||u===g?u=p:u===_||u===m?u=f:(u=p,l=void 0);const w=u===p&&t[i+1].startsWith(\"/>\")?\" \":\"\";r+=u===f?s+h:v>=0?(e.push(d),s.slice(0,v)+o+s.slice(v)+n+w):s+n+(-2===v?(e.push(void 0),i):w)}return[P(t,r+(t[s]||\"<?>\")+(2===i?\"</svg>\":\"\")),e]};class N{constructor({strings:t,_$litType$:i},e){let h;this.parts=[];let r=0,d=0;const c=t.length-1,v=this.parts,[a,f]=V(t,i);if(this.el=N.createElement(a,e),C.currentNode=this.el.content,2===i){const t=this.el.content,i=t.firstChild;i.remove(),t.append(...i.childNodes)}for(;null!==(h=C.nextNode())&&v.length<c;){if(1===h.nodeType){if(h.hasAttributes()){const t=[];for(const i of h.getAttributeNames())if(i.endsWith(o)||i.startsWith(n)){const s=f[d++];if(t.push(i),void 0!==s){const t=h.getAttribute(s.toLowerCase()+o).split(n),i=/([.?@])?(.*)/.exec(s);v.push({type:1,index:r,name:i[2],strings:t,ctor:\".\"===i[1]?H:\"?\"===i[1]?L:\"@\"===i[1]?z:k})}else v.push({type:6,index:r})}for(const i of t)h.removeAttribute(i)}if(y.test(h.tagName)){const t=h.textContent.split(n),i=t.length-1;if(i>0){h.textContent=s?s.emptyScript:\"\";for(let s=0;s<i;s++)h.append(t[s],u()),C.nextNode(),v.push({type:2,index:++r});h.append(t[i],u())}}}else if(8===h.nodeType)if(h.data===l)v.push({type:2,index:r});else{let t=-1;for(;-1!==(t=h.data.indexOf(n,t+1));)v.push({type:7,index:r}),t+=n.length-1}r++}}static createElement(t,i){const s=r.createElement(\"template\");return s.innerHTML=t,s}}function S(t,i,s=t,e){var o,n,l,h;if(i===T)return i;let r=void 0!==e?null===(o=s._$Co)||void 0===o?void 0:o[e]:s._$Cl;const u=d(i)?void 0:i._$litDirective$;return(null==r?void 0:r.constructor)!==u&&(null===(n=null==r?void 0:r._$AO)||void 0===n||n.call(r,!1),void 0===u?r=void 0:(r=new u(t),r._$AT(t,s,e)),void 0!==e?(null!==(l=(h=s)._$Co)&&void 0!==l?l:h._$Co=[])[e]=r:s._$Cl=r),void 0!==r&&(i=S(t,r._$AS(t,i.values),r,e)),i}class M{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){var i;const{el:{content:s},parts:e}=this._$AD,o=(null!==(i=null==t?void 0:t.creationScope)&&void 0!==i?i:r).importNode(s,!0);C.currentNode=o;let n=C.nextNode(),l=0,h=0,u=e[0];for(;void 0!==u;){if(l===u.index){let i;2===u.type?i=new R(n,n.nextSibling,this,t):1===u.type?i=new u.ctor(n,u.name,u.strings,this,t):6===u.type&&(i=new Z(n,this,t)),this._$AV.push(i),u=e[++h]}l!==(null==u?void 0:u.index)&&(n=C.nextNode(),l++)}return C.currentNode=r,o}v(t){let i=0;for(const s of this._$AV)void 0!==s&&(void 0!==s.strings?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class R{constructor(t,i,s,e){var o;this.type=2,this._$AH=A,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=e,this._$Cp=null===(o=null==e?void 0:e.isConnected)||void 0===o||o}get _$AU(){var t,i;return null!==(i=null===(t=this._$AM)||void 0===t?void 0:t._$AU)&&void 0!==i?i:this._$Cp}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return void 0!==i&&11===(null==t?void 0:t.nodeType)&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=S(this,t,i),d(t)?t===A||null==t||\"\"===t?(this._$AH!==A&&this._$AR(),this._$AH=A):t!==this._$AH&&t!==T&&this._(t):void 0!==t._$litType$?this.g(t):void 0!==t.nodeType?this.$(t):v(t)?this.T(t):this._(t)}k(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}$(t){this._$AH!==t&&(this._$AR(),this._$AH=this.k(t))}_(t){this._$AH!==A&&d(this._$AH)?this._$AA.nextSibling.data=t:this.$(r.createTextNode(t)),this._$AH=t}g(t){var i;const{values:s,_$litType$:e}=t,o=\"number\"==typeof e?this._$AC(t):(void 0===e.el&&(e.el=N.createElement(P(e.h,e.h[0]),this.options)),e);if((null===(i=this._$AH)||void 0===i?void 0:i._$AD)===o)this._$AH.v(s);else{const t=new M(o,this),i=t.u(this.options);t.v(s),this.$(i),this._$AH=t}}_$AC(t){let i=E.get(t.strings);return void 0===i&&E.set(t.strings,i=new N(t)),i}T(t){c(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,e=0;for(const o of t)e===i.length?i.push(s=new R(this.k(u()),this.k(u()),this,this.options)):s=i[e],s._$AI(o),e++;e<i.length&&(this._$AR(s&&s._$AB.nextSibling,e),i.length=e)}_$AR(t=this._$AA.nextSibling,i){var s;for(null===(s=this._$AP)||void 0===s||s.call(this,!1,!0,i);t&&t!==this._$AB;){const i=t.nextSibling;t.remove(),t=i}}setConnected(t){var i;void 0===this._$AM&&(this._$Cp=t,null===(i=this._$AP)||void 0===i||i.call(this,t))}}class k{constructor(t,i,s,e,o){this.type=1,this._$AH=A,this._$AN=void 0,this.element=t,this.name=i,this._$AM=e,this.options=o,s.length>2||\"\"!==s[0]||\"\"!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=A}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,i=this,s,e){const o=this.strings;let n=!1;if(void 0===o)t=S(this,t,i,0),n=!d(t)||t!==this._$AH&&t!==T,n&&(this._$AH=t);else{const e=t;let l,h;for(t=o[0],l=0;l<o.length-1;l++)h=S(this,e[s+l],i,l),h===T&&(h=this._$AH[l]),n||(n=!d(h)||h!==this._$AH[l]),h===A?t=A:t!==A&&(t+=(null!=h?h:\"\")+o[l+1]),this._$AH[l]=h}n&&!e&&this.j(t)}j(t){t===A?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,null!=t?t:\"\")}}class H extends k{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===A?void 0:t}}const I=s?s.emptyScript:\"\";class L extends k{constructor(){super(...arguments),this.type=4}j(t){t&&t!==A?this.element.setAttribute(this.name,I):this.element.removeAttribute(this.name)}}class z extends k{constructor(t,i,s,e,o){super(t,i,s,e,o),this.type=5}_$AI(t,i=this){var s;if((t=null!==(s=S(this,t,i,0))&&void 0!==s?s:A)===T)return;const e=this._$AH,o=t===A&&e!==A||t.capture!==e.capture||t.once!==e.once||t.passive!==e.passive,n=t!==A&&(e===A||o);o&&this.element.removeEventListener(this.name,this,e),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var i,s;\"function\"==typeof this._$AH?this._$AH.call(null!==(s=null===(i=this.options)||void 0===i?void 0:i.host)&&void 0!==s?s:this.element,t):this._$AH.handleEvent(t)}}class Z{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){S(this,t)}}const j={O:o,P:n,A:l,C:1,M:V,L:M,D:v,R:S,I:R,V:k,H:L,N:z,U:H,F:Z},B=i.litHtmlPolyfillSupport;null==B||B(N,R),(null!==(t=i.litHtmlVersions)&&void 0!==t?t:i.litHtmlVersions=[]).push(\"2.7.5\");const D=(t,i,s)=>{var e,o;const n=null!==(e=null==s?void 0:s.renderBefore)&&void 0!==e?e:i;let l=n._$litPart$;if(void 0===l){const t=null!==(o=null==s?void 0:s.renderBefore)&&void 0!==o?o:null;n._$litPart$=l=new R(i.insertBefore(u(),t),t,void 0,null!=s?s:{})}return l._$AI(t),l};export{j as _$LH,x as html,T as noChange,A as nothing,D as render,b as svg};\n//# sourceMappingURL=lit-html.js.map\n","import{ReactiveElement as t}from\"@lit/reactive-element\";export*from\"@lit/reactive-element\";import{render as e,noChange as i}from\"lit-html\";export*from\"lit-html\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */var l,o;const r=t;class s extends t{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t,e;const i=super.createRenderRoot();return null!==(t=(e=this.renderOptions).renderBefore)&&void 0!==t||(e.renderBefore=i.firstChild),i}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=e(i,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!1)}render(){return i}}s.finalized=!0,s._$litElement$=!0,null===(l=globalThis.litElementHydrateSupport)||void 0===l||l.call(globalThis,{LitElement:s});const n=globalThis.litElementPolyfillSupport;null==n||n({LitElement:s});const h={_$AK:(t,e,i)=>{t._$AK(e,i)},_$AL:t=>t._$AL};(null!==(o=globalThis.litElementVersions)&&void 0!==o?o:globalThis.litElementVersions=[]).push(\"3.3.2\");export{s as LitElement,r as UpdatingElement,h as _$LE};\n//# sourceMappingURL=lit-element.js.map\n","/**\n * @license\n * Copyright 2022 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { html, LitElement } from 'lit';\n/**\n * A component for elevation.\n */\nexport class Elevation extends LitElement {\n    render() {\n        return html `<span class=\"shadow\"></span>`;\n    }\n}\n//# sourceMappingURL=elevation.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_level: var(--md-elevation-level, 0);--_shadow-color: var(--md-elevation-shadow-color, var(--md-sys-color-shadow, #000));display:flex;pointer-events:none}:host,.shadow,.shadow::before,.shadow::after{border-radius:inherit;inset:0;position:absolute;transition-duration:inherit;transition-timing-function:inherit}.shadow::before,.shadow::after{content:\"\";transition-property:box-shadow,opacity}.shadow::before{box-shadow:0px calc(1px*(clamp(0,var(--_level),1) + clamp(0,var(--_level) - 3,1) + 2*clamp(0,var(--_level) - 4,1))) calc(1px*(2*clamp(0,var(--_level),1) + clamp(0,var(--_level) - 2,1) + clamp(0,var(--_level) - 4,1))) 0px var(--_shadow-color);opacity:.3}.shadow::after{box-shadow:0px calc(1px*(clamp(0,var(--_level),1) + clamp(0,var(--_level) - 1,1) + 2*clamp(0,var(--_level) - 2,3))) calc(1px*(3*clamp(0,var(--_level),2) + 2*clamp(0,var(--_level) - 2,3))) calc(1px*(clamp(0,var(--_level),4) + 2*clamp(0,var(--_level) - 4,1))) var(--_shadow-color);opacity:.15}/*# sourceMappingURL=elevation-styles.css.map */\n`;\n//# sourceMappingURL=elevation-styles.css.js.map","/**\n * @license\n * Copyright 2022 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { Elevation } from './internal/elevation.js';\nimport { styles } from './internal/elevation-styles.css.js';\n/**\n * The `<md-elevation>` custom element with default styles.\n *\n * Elevation is the relative distance between two surfaces along the z-axis.\n */\nlet MdElevation = class MdElevation extends Elevation {\n};\nMdElevation.styles = [styles];\nMdElevation = __decorate([\n    customElement('md-elevation')\n], MdElevation);\nexport { MdElevation };\n//# sourceMappingURL=elevation.js.map","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { isServer } from 'lit';\n/**\n * A key to retrieve an `Attachable` element's `AttachableController` from a\n * global `MutationObserver`.\n */\nconst ATTACHABLE_CONTROLLER = Symbol('attachableController');\nlet FOR_ATTRIBUTE_OBSERVER;\nif (!isServer) {\n    /**\n     * A global `MutationObserver` that reacts to `for` attribute changes on\n     * `Attachable` elements. If the `for` attribute changes, the controller will\n     * re-attach to the new referenced element.\n     */\n    FOR_ATTRIBUTE_OBSERVER = new MutationObserver(records => {\n        for (const record of records) {\n            // When a control's `for` attribute changes, inform its\n            // `AttachableController` to update to a new control.\n            record.target[ATTACHABLE_CONTROLLER]\n                ?.hostConnected();\n        }\n    });\n}\n/**\n * A controller that provides an implementation for `Attachable` elements.\n *\n * @example\n * ```ts\n * class MyElement extends LitElement implements Attachable {\n *   get control() { return this.attachableController.control; }\n *\n *   private readonly attachableController = new AttachableController(\n *     this,\n *     (previousControl, newControl) => {\n *       previousControl?.removeEventListener('click', this.handleClick);\n *       newControl?.addEventListener('click', this.handleClick);\n *     }\n *   );\n *\n *   // Implement remaining `Attachable` properties/methods that call the\n *   // controller's properties/methods.\n * }\n * ```\n */\nexport class AttachableController {\n    get htmlFor() {\n        return this.host.getAttribute('for');\n    }\n    set htmlFor(htmlFor) {\n        if (htmlFor === null) {\n            this.host.removeAttribute('for');\n        }\n        else {\n            this.host.setAttribute('for', htmlFor);\n        }\n    }\n    get control() {\n        if (this.host.hasAttribute('for')) {\n            if (!this.htmlFor || !this.host.isConnected) {\n                return null;\n            }\n            return this.host.getRootNode()\n                .querySelector(`#${this.htmlFor}`);\n        }\n        return this.currentControl || this.host.parentElement;\n    }\n    /**\n     * Creates a new controller for an `Attachable` element.\n     *\n     * @param host The `Attachable` element.\n     * @param onControlChange A callback with two parameters for the previous and\n     *     next control. An `Attachable` element may perform setup or teardown\n     *     logic whenever the control changes.\n     */\n    constructor(host, onControlChange) {\n        this.host = host;\n        this.onControlChange = onControlChange;\n        this.currentControl = null;\n        host.addController(this);\n        host[ATTACHABLE_CONTROLLER] = this;\n        FOR_ATTRIBUTE_OBSERVER?.observe(host, { attributeFilter: ['for'] });\n    }\n    attach(control) {\n        if (control === this.currentControl) {\n            return;\n        }\n        this.setCurrentControl(control);\n        // When imperatively attaching, remove the `for` attribute so\n        // that the attached control is used instead of a referenced one.\n        this.host.removeAttribute('for');\n    }\n    detach() {\n        this.setCurrentControl(null);\n        // When imperatively detaching, add an empty `for=\"\"` attribute. This will\n        // ensure the control is `null` rather than the `parentElement`.\n        this.host.setAttribute('for', '');\n    }\n    /** @private */\n    hostConnected() {\n        this.setCurrentControl(this.control);\n    }\n    /** @private */\n    hostDisconnected() {\n        this.setCurrentControl(null);\n    }\n    setCurrentControl(control) {\n        this.onControlChange(this.currentControl, control);\n        this.currentControl = control;\n    }\n}\n//# sourceMappingURL=attachable-controller.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { LitElement } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { AttachableController } from '../../internal/controller/attachable-controller.js';\n/**\n * Events that the focus ring listens to.\n */\nconst EVENTS = ['focusin', 'focusout', 'pointerdown'];\n/**\n * A focus ring component.\n */\nexport class FocusRing extends LitElement {\n    constructor() {\n        super(...arguments);\n        /**\n         * Makes the focus ring visible.\n         */\n        this.visible = false;\n        /**\n         * Makes the focus ring animate inwards instead of outwards.\n         */\n        this.inward = false;\n        this.attachableController = new AttachableController(this, this.onControlChange.bind(this));\n    }\n    get htmlFor() {\n        return this.attachableController.htmlFor;\n    }\n    set htmlFor(htmlFor) {\n        this.attachableController.htmlFor = htmlFor;\n    }\n    get control() {\n        return this.attachableController.control;\n    }\n    attach(control) {\n        this.attachableController.attach(control);\n    }\n    detach() {\n        this.attachableController.detach();\n    }\n    /** @private */\n    handleEvent(event) {\n        if (event[HANDLED_BY_FOCUS_RING]) {\n            // This ensures the focus ring does not activate when multiple focus rings\n            // are used within a single component.\n            return;\n        }\n        switch (event.type) {\n            default:\n                return;\n            case 'focusin':\n                this.visible = this.control?.matches(':focus-visible') ?? false;\n                break;\n            case 'focusout':\n            case 'pointerdown':\n                this.visible = false;\n                break;\n        }\n        event[HANDLED_BY_FOCUS_RING] = true;\n    }\n    onControlChange(prev, next) {\n        for (const event of EVENTS) {\n            prev?.removeEventListener(event, this);\n            next?.addEventListener(event, this);\n        }\n    }\n}\n__decorate([\n    property({ type: Boolean, reflect: true })\n], FocusRing.prototype, \"visible\", void 0);\n__decorate([\n    property({ type: Boolean, reflect: true })\n], FocusRing.prototype, \"inward\", void 0);\nconst HANDLED_BY_FOCUS_RING = Symbol('handledByFocusRing');\n//# sourceMappingURL=focus-ring.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--md-focus-ring-active-width: 8px;--md-focus-ring-color: var(--md-sys-color-secondary, #625b71);--md-focus-ring-duration: 600ms;--md-focus-ring-inward-offset: 0px;--md-focus-ring-outward-offset: 2px;--md-focus-ring-shape: 9999px;--md-focus-ring-width: 3px;--md-focus-ring-shape-start-start: var(--md-focus-ring-shape);--md-focus-ring-shape-start-end: var(--md-focus-ring-shape);--md-focus-ring-shape-end-end: var(--md-focus-ring-shape);--md-focus-ring-shape-end-start: var(--md-focus-ring-shape);animation-delay:0s,calc(var(--md-focus-ring-duration)*.25);animation-duration:calc(var(--md-focus-ring-duration)*.25),calc(var(--md-focus-ring-duration)*.75);animation-timing-function:cubic-bezier(0.2, 0, 0, 1);box-sizing:border-box;color:var(--md-focus-ring-color);display:none;pointer-events:none;position:absolute}:host([visible]){display:flex}:host(:not([inward])){animation-name:outward-grow,outward-shrink;border-end-end-radius:calc(var(--md-focus-ring-shape-end-end) + var(--md-focus-ring-outward-offset));border-end-start-radius:calc(var(--md-focus-ring-shape-end-start) + var(--md-focus-ring-outward-offset));border-start-end-radius:calc(var(--md-focus-ring-shape-start-end) + var(--md-focus-ring-outward-offset));border-start-start-radius:calc(var(--md-focus-ring-shape-start-start) + var(--md-focus-ring-outward-offset));inset:calc(-1*(var(--md-focus-ring-outward-offset)));outline:var(--md-focus-ring-width) solid currentColor}:host([inward]){animation-name:inward-grow,inward-shrink;border-end-end-radius:calc(var(--md-focus-ring-shape-end-end) - var(--md-focus-ring-inward-offset));border-end-start-radius:calc(var(--md-focus-ring-shape-end-start) - var(--md-focus-ring-inward-offset));border-start-end-radius:calc(var(--md-focus-ring-shape-start-end) - var(--md-focus-ring-inward-offset));border-start-start-radius:calc(var(--md-focus-ring-shape-start-start) - var(--md-focus-ring-inward-offset));border:var(--md-focus-ring-width) solid currentColor;inset:var(--md-focus-ring-inward-offset)}@keyframes outward-grow{from{outline-width:0}to{outline-width:var(--md-focus-ring-active-width)}}@keyframes outward-shrink{from{outline-width:var(--md-focus-ring-active-width)}}@keyframes inward-grow{from{border-width:0}to{border-width:var(--md-focus-ring-active-width)}}@keyframes inward-shrink{from{border-width:var(--md-focus-ring-active-width)}}@media(prefers-reduced-motion){:host{animation:none}}/*# sourceMappingURL=focus-ring-styles.css.map */\n`;\n//# sourceMappingURL=focus-ring-styles.css.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { FocusRing } from './internal/focus-ring.js';\nimport { styles } from './internal/focus-ring-styles.css.js';\n/**\n * TODO(b/267336424): add docs\n *\n * @final\n * @suppress {visibility}\n */\nlet MdFocusRing = class MdFocusRing extends FocusRing {\n};\nMdFocusRing.styles = [styles];\nMdFocusRing = __decorate([\n    customElement('md-focus-ring')\n], MdFocusRing);\nexport { MdFocusRing };\n//# sourceMappingURL=md-focus-ring.js.map","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},e=t=>(...e)=>({_$litDirective$:t,values:e});class i{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}export{i as Directive,t as PartType,e as directive};\n//# sourceMappingURL=directive.js.map\n","import{noChange as t}from\"../lit-html.js\";import{directive as i,Directive as s,PartType as r}from\"../directive.js\";\n/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const o=i(class extends s{constructor(t){var i;if(super(t),t.type!==r.ATTRIBUTE||\"class\"!==t.name||(null===(i=t.strings)||void 0===i?void 0:i.length)>2)throw Error(\"`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.\")}render(t){return\" \"+Object.keys(t).filter((i=>t[i])).join(\" \")+\" \"}update(i,[s]){var r,o;if(void 0===this.it){this.it=new Set,void 0!==i.strings&&(this.nt=new Set(i.strings.join(\" \").split(/\\s/).filter((t=>\"\"!==t))));for(const t in s)s[t]&&!(null===(r=this.nt)||void 0===r?void 0:r.has(t))&&this.it.add(t);return this.render(s)}const e=i.element.classList;this.it.forEach((t=>{t in s||(e.remove(t),this.it.delete(t))}));for(const t in s){const i=!!s[t];i===this.it.has(t)||(null===(o=this.nt)||void 0===o?void 0:o.has(t))||(i?(e.add(t),this.it.add(t)):(e.remove(t),this.it.delete(t)))}return t}});export{o as classMap};\n//# sourceMappingURL=class-map.js.map\n","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * Easing functions to use for web animations.\n *\n * **NOTE:** `EASING.EMPHASIZED` is approximated with unknown accuracy.\n *\n * TODO(b/241113345): replace with tokens\n */\nexport const EASING = {\n    STANDARD: 'cubic-bezier(0.2, 0, 0, 1)',\n    STANDARD_ACCELERATE: 'cubic-bezier(.3,0,1,1)',\n    STANDARD_DECELERATE: 'cubic-bezier(0,0,0,1)',\n    EMPHASIZED: 'cubic-bezier(.3,0,0,1)',\n    EMPHASIZED_ACCELERATE: 'cubic-bezier(.3,0,.8,.15)',\n    EMPHASIZED_DECELERATE: 'cubic-bezier(.05,.7,.1,1)',\n};\n/**\n * Creates an `AnimationSignal` that can be used to cancel a previous task.\n *\n * @example\n * class MyClass {\n *   private labelAnimationSignal = createAnimationSignal();\n *\n *   private async animateLabel() {\n *     // Start of the task. Previous tasks will be canceled.\n *     const signal = this.labelAnimationSignal.start();\n *\n *     // Do async work...\n *     if (signal.aborted) {\n *       // Use AbortSignal to check if a request was made to abort after some\n *       // asynchronous work.\n *       return;\n *     }\n *\n *     const animation = this.animate(...);\n *     // Add event listeners to be notified when the task should be canceled.\n *     signal.addEventListener('abort', () => {\n *       animation.cancel();\n *     });\n *\n *     animation.addEventListener('finish', () => {\n *       // Tell the signal that the current task is finished.\n *       this.labelAnimationSignal.finish();\n *     });\n *   }\n * }\n *\n * @return An `AnimationSignal`.\n */\nexport function createAnimationSignal() {\n    // The current animation's AbortController\n    let animationAbortController = null;\n    return {\n        start() {\n            // Tell the previous animation to cancel.\n            animationAbortController?.abort();\n            // Set up a new AbortController for the current animation.\n            animationAbortController = new AbortController();\n            // Provide the AbortSignal so that the caller can check aborted status\n            // and add listeners.\n            return animationAbortController.signal;\n        },\n        finish() {\n            animationAbortController = null;\n        },\n    };\n}\n/**\n * Returns a function which can be used to throttle function calls\n * mapped to a key via a given function that should produce a promise that\n * determines the throttle amount (defaults to requestAnimationFrame).\n */\nexport function createThrottle() {\n    const stack = new Set();\n    return async (key = '', cb, timeout = async () => {\n        await new Promise(requestAnimationFrame);\n    }) => {\n        if (!stack.has(key)) {\n            stack.add(key);\n            await timeout();\n            if (stack.has(key)) {\n                stack.delete(key);\n                cb();\n            }\n        }\n    };\n}\n/**\n * Parses an number in milliseconds from a css time value\n */\nexport function msFromTimeCSSValue(value) {\n    const match = value.trim().match(/([\\d.]+)(\\s*s$)?/);\n    const time = match?.[1];\n    const seconds = match?.[2];\n    return Number(time ?? 0) * (seconds ? 1000 : 1);\n}\n//# sourceMappingURL=animation.js.map","/**\n * @license\n * Copyright 2022 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { html, LitElement } from 'lit';\nimport { property, query, state } from 'lit/decorators.js';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { AttachableController } from '../../internal/controller/attachable-controller.js';\nimport { EASING } from '../../internal/motion/animation.js';\nconst PRESS_GROW_MS = 450;\nconst MINIMUM_PRESS_MS = 225;\nconst INITIAL_ORIGIN_SCALE = 0.2;\nconst PADDING = 10;\nconst SOFT_EDGE_MINIMUM_SIZE = 75;\nconst SOFT_EDGE_CONTAINER_RATIO = 0.35;\nconst PRESS_PSEUDO = '::after';\nconst ANIMATION_FILL = 'forwards';\n/**\n * Interaction states for the ripple.\n *\n * On Touch:\n *  - `INACTIVE -> TOUCH_DELAY -> WAITING_FOR_CLICK -> INACTIVE`\n *  - `INACTIVE -> TOUCH_DELAY -> HOLDING -> WAITING_FOR_CLICK -> INACTIVE`\n *\n * On Mouse or Pen:\n *   - `INACTIVE -> WAITING_FOR_CLICK -> INACTIVE`\n */\nvar State;\n(function (State) {\n    /**\n     * Initial state of the control, no touch in progress.\n     *\n     * Transitions:\n     *   - on touch down: transition to `TOUCH_DELAY`.\n     *   - on mouse down: transition to `WAITING_FOR_CLICK`.\n     */\n    State[State[\"INACTIVE\"] = 0] = \"INACTIVE\";\n    /**\n     * Touch down has been received, waiting to determine if it's a swipe or\n     * scroll.\n     *\n     * Transitions:\n     *   - on touch up: begin press; transition to `WAITING_FOR_CLICK`.\n     *   - on cancel: transition to `INACTIVE`.\n     *   - after `TOUCH_DELAY_MS`: begin press; transition to `HOLDING`.\n     */\n    State[State[\"TOUCH_DELAY\"] = 1] = \"TOUCH_DELAY\";\n    /**\n     * A touch has been deemed to be a press\n     *\n     * Transitions:\n     *  - on up: transition to `WAITING_FOR_CLICK`.\n     */\n    State[State[\"HOLDING\"] = 2] = \"HOLDING\";\n    /**\n     * The user touch has finished, transition into rest state.\n     *\n     * Transitions:\n     *   - on click end press; transition to `INACTIVE`.\n     */\n    State[State[\"WAITING_FOR_CLICK\"] = 3] = \"WAITING_FOR_CLICK\";\n})(State || (State = {}));\n/**\n * Events that the ripple listens to.\n */\nconst EVENTS = [\n    'click', 'contextmenu', 'pointercancel', 'pointerdown', 'pointerenter',\n    'pointerleave', 'pointerup'\n];\n/**\n * Delay reacting to touch so that we do not show the ripple for a swipe or\n * scroll interaction.\n */\nconst TOUCH_DELAY_MS = 150;\n/**\n * A ripple component.\n */\nexport class Ripple extends LitElement {\n    constructor() {\n        super(...arguments);\n        /**\n         * Disables the ripple.\n         */\n        this.disabled = false;\n        this.hovered = false;\n        this.pressed = false;\n        this.rippleSize = '';\n        this.rippleScale = '';\n        this.initialSize = 0;\n        this.state = State.INACTIVE;\n        this.checkBoundsAfterContextMenu = false;\n        this.attachableController = new AttachableController(this, this.onControlChange.bind(this));\n    }\n    get htmlFor() {\n        return this.attachableController.htmlFor;\n    }\n    set htmlFor(htmlFor) {\n        this.attachableController.htmlFor = htmlFor;\n    }\n    get control() {\n        return this.attachableController.control;\n    }\n    attach(control) {\n        this.attachableController.attach(control);\n    }\n    detach() {\n        this.attachableController.detach();\n    }\n    render() {\n        const classes = {\n            'hovered': this.hovered,\n            'pressed': this.pressed,\n        };\n        return html `<div class=\"surface ${classMap(classes)}\"></div>`;\n    }\n    update(changedProps) {\n        if (changedProps.has('disabled') && this.disabled) {\n            this.hovered = false;\n            this.pressed = false;\n        }\n        super.update(changedProps);\n    }\n    /**\n     * TODO(b/269799771): make private\n     * @private only public for slider\n     */\n    handlePointerenter(event) {\n        if (!this.shouldReactToEvent(event)) {\n            return;\n        }\n        this.hovered = true;\n    }\n    /**\n     * TODO(b/269799771): make private\n     * @private only public for slider\n     */\n    handlePointerleave(event) {\n        if (!this.shouldReactToEvent(event)) {\n            return;\n        }\n        this.hovered = false;\n        // release a held mouse or pen press that moves outside the element\n        if (this.state !== State.INACTIVE) {\n            this.endPressAnimation();\n        }\n    }\n    handlePointerup(event) {\n        if (!this.shouldReactToEvent(event)) {\n            return;\n        }\n        if (this.state === State.HOLDING) {\n            this.state = State.WAITING_FOR_CLICK;\n            return;\n        }\n        if (this.state === State.TOUCH_DELAY) {\n            this.state = State.WAITING_FOR_CLICK;\n            this.startPressAnimation(this.rippleStartEvent);\n            return;\n        }\n    }\n    async handlePointerdown(event) {\n        if (!this.shouldReactToEvent(event)) {\n            return;\n        }\n        this.rippleStartEvent = event;\n        if (!this.isTouch(event)) {\n            this.state = State.WAITING_FOR_CLICK;\n            this.startPressAnimation(event);\n            return;\n        }\n        // after a longpress contextmenu event, an extra `pointerdown` can be\n        // dispatched to the pressed element. Check that the down is within\n        // bounds of the element in this case.\n        if (this.checkBoundsAfterContextMenu && !this.inBounds(event)) {\n            return;\n        }\n        this.checkBoundsAfterContextMenu = false;\n        // Wait for a hold after touch delay\n        this.state = State.TOUCH_DELAY;\n        await new Promise(resolve => {\n            setTimeout(resolve, TOUCH_DELAY_MS);\n        });\n        if (this.state !== State.TOUCH_DELAY) {\n            return;\n        }\n        this.state = State.HOLDING;\n        this.startPressAnimation(event);\n    }\n    handleClick() {\n        // Click is a MouseEvent in Firefox and Safari, so we cannot use\n        // `shouldReactToEvent`\n        if (this.disabled) {\n            return;\n        }\n        if (this.state === State.WAITING_FOR_CLICK) {\n            this.endPressAnimation();\n            return;\n        }\n        if (this.state === State.INACTIVE) {\n            // keyboard synthesized click event\n            this.startPressAnimation();\n            this.endPressAnimation();\n        }\n    }\n    handlePointercancel(event) {\n        if (!this.shouldReactToEvent(event)) {\n            return;\n        }\n        this.endPressAnimation();\n    }\n    handleContextmenu() {\n        if (this.disabled) {\n            return;\n        }\n        this.checkBoundsAfterContextMenu = true;\n        this.endPressAnimation();\n    }\n    determineRippleSize() {\n        const { height, width } = this.getBoundingClientRect();\n        const maxDim = Math.max(height, width);\n        const softEdgeSize = Math.max(SOFT_EDGE_CONTAINER_RATIO * maxDim, SOFT_EDGE_MINIMUM_SIZE);\n        const initialSize = Math.floor(maxDim * INITIAL_ORIGIN_SCALE);\n        const hypotenuse = Math.sqrt(width ** 2 + height ** 2);\n        const maxRadius = hypotenuse + PADDING;\n        this.initialSize = initialSize;\n        this.rippleScale = `${(maxRadius + softEdgeSize) / initialSize}`;\n        this.rippleSize = `${initialSize}px`;\n    }\n    getNormalizedPointerEventCoords(pointerEvent) {\n        const { scrollX, scrollY } = window;\n        const { left, top } = this.getBoundingClientRect();\n        const documentX = scrollX + left;\n        const documentY = scrollY + top;\n        const { pageX, pageY } = pointerEvent;\n        return { x: pageX - documentX, y: pageY - documentY };\n    }\n    getTranslationCoordinates(positionEvent) {\n        const { height, width } = this.getBoundingClientRect();\n        // end in the center\n        const endPoint = {\n            x: (width - this.initialSize) / 2,\n            y: (height - this.initialSize) / 2,\n        };\n        let startPoint;\n        if (positionEvent instanceof PointerEvent) {\n            startPoint = this.getNormalizedPointerEventCoords(positionEvent);\n        }\n        else {\n            startPoint = {\n                x: width / 2,\n                y: height / 2,\n            };\n        }\n        // center around start point\n        startPoint = {\n            x: startPoint.x - (this.initialSize / 2),\n            y: startPoint.y - (this.initialSize / 2),\n        };\n        return { startPoint, endPoint };\n    }\n    startPressAnimation(positionEvent) {\n        if (!this.mdRoot) {\n            return;\n        }\n        this.pressed = true;\n        this.growAnimation?.cancel();\n        this.determineRippleSize();\n        const { startPoint, endPoint } = this.getTranslationCoordinates(positionEvent);\n        const translateStart = `${startPoint.x}px, ${startPoint.y}px`;\n        const translateEnd = `${endPoint.x}px, ${endPoint.y}px`;\n        this.growAnimation = this.mdRoot.animate({\n            top: [0, 0],\n            left: [0, 0],\n            height: [this.rippleSize, this.rippleSize],\n            width: [this.rippleSize, this.rippleSize],\n            transform: [\n                `translate(${translateStart}) scale(1)`,\n                `translate(${translateEnd}) scale(${this.rippleScale})`\n            ],\n        }, {\n            pseudoElement: PRESS_PSEUDO,\n            duration: PRESS_GROW_MS,\n            easing: EASING.STANDARD,\n            fill: ANIMATION_FILL\n        });\n    }\n    async endPressAnimation() {\n        this.state = State.INACTIVE;\n        const animation = this.growAnimation;\n        const pressAnimationPlayState = animation?.currentTime ?? Infinity;\n        // TODO: go/ts51upgrade - Auto-added to unblock TS5.1 migration.\n        //   TS2365: Operator '>=' cannot be applied to types 'CSSNumberish' and\n        //   'number'.\n        // @ts-ignore\n        if (pressAnimationPlayState >= MINIMUM_PRESS_MS) {\n            this.pressed = false;\n            return;\n        }\n        await new Promise(resolve => {\n            // TODO: go/ts51upgrade - Auto-added to unblock TS5.1 migration.\n            //   TS2363: The right-hand side of an arithmetic operation must be of\n            //   type 'any', 'number', 'bigint' or an enum type.\n            // @ts-ignore\n            setTimeout(resolve, MINIMUM_PRESS_MS - pressAnimationPlayState);\n        });\n        if (this.growAnimation !== animation) {\n            // A new press animation was started. The old animation was canceled and\n            // should not finish the pressed state.\n            return;\n        }\n        this.pressed = false;\n    }\n    /**\n     * Returns `true` if\n     *  - the ripple element is enabled\n     *  - the pointer is primary for the input type\n     *  - the pointer is the pointer that started the interaction, or will start\n     * the interaction\n     *  - the pointer is a touch, or the pointer state has the primary button\n     * held, or the pointer is hovering\n     */\n    shouldReactToEvent(event) {\n        if (this.disabled || !event.isPrimary) {\n            return false;\n        }\n        if (this.rippleStartEvent &&\n            this.rippleStartEvent.pointerId !== event.pointerId) {\n            return false;\n        }\n        if (event.type === 'pointerenter' || event.type === 'pointerleave') {\n            return !this.isTouch(event);\n        }\n        const isPrimaryButton = event.buttons === 1;\n        return this.isTouch(event) || isPrimaryButton;\n    }\n    /**\n     * Check if the event is within the bounds of the element.\n     *\n     * This is only needed for the \"stuck\" contextmenu longpress on Chrome.\n     */\n    inBounds({ x, y }) {\n        const { top, left, bottom, right } = this.getBoundingClientRect();\n        return x >= left && x <= right && y >= top && y <= bottom;\n    }\n    isTouch({ pointerType }) {\n        return pointerType === 'touch';\n    }\n    /** @private */\n    async handleEvent(event) {\n        switch (event.type) {\n            case 'click':\n                this.handleClick();\n                break;\n            case 'contextmenu':\n                this.handleContextmenu();\n                break;\n            case 'pointercancel':\n                this.handlePointercancel(event);\n                break;\n            case 'pointerdown':\n                await this.handlePointerdown(event);\n                break;\n            case 'pointerenter':\n                this.handlePointerenter(event);\n                break;\n            case 'pointerleave':\n                this.handlePointerleave(event);\n                break;\n            case 'pointerup':\n                this.handlePointerup(event);\n                break;\n            default:\n                break;\n        }\n    }\n    onControlChange(prev, next) {\n        for (const event of EVENTS) {\n            prev?.removeEventListener(event, this);\n            next?.addEventListener(event, this);\n        }\n    }\n}\n__decorate([\n    property({ type: Boolean, reflect: true })\n], Ripple.prototype, \"disabled\", void 0);\n__decorate([\n    state()\n], Ripple.prototype, \"hovered\", void 0);\n__decorate([\n    state()\n], Ripple.prototype, \"pressed\", void 0);\n__decorate([\n    query('.surface')\n], Ripple.prototype, \"mdRoot\", void 0);\n//# sourceMappingURL=ripple.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_hover-color: var(--md-ripple-hover-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-opacity: var(--md-ripple-hover-opacity, 0.08);--_pressed-color: var(--md-ripple-pressed-color, var(--md-sys-color-on-surface, #1d1b20));--_pressed-opacity: var(--md-ripple-pressed-opacity, 0.12);display:flex;margin:auto;pointer-events:none}:host([disabled]){display:none}@media screen and (forced-colors: active){:host{display:none}}:host,.surface{border-radius:inherit;position:absolute;inset:0;overflow:hidden}.surface{-webkit-tap-highlight-color:rgba(0,0,0,0)}.surface::before,.surface::after{content:\"\";opacity:0;position:absolute}.surface::before{background-color:var(--_hover-color);inset:0;transition:opacity 15ms linear,background-color 15ms linear}.surface::after{background:radial-gradient(closest-side, var(--_pressed-color) max(100% - 70px, 65%), transparent 100%);transform-origin:center center;transition:opacity 375ms linear}.hovered::before{background-color:var(--_hover-color);opacity:var(--_hover-opacity)}.pressed::after{opacity:var(--_pressed-opacity);transition-duration:105ms}/*# sourceMappingURL=ripple-styles.css.map */\n`;\n//# sourceMappingURL=ripple-styles.css.js.map","/**\n * @license\n * Copyright 2022 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { Ripple } from './internal/ripple.js';\nimport { styles } from './internal/ripple-styles.css.js';\n/**\n * @summary Ripples, also known as state layers, are visual indicators used to\n * communicate the status of a component or interactive element.\n *\n * @description A state layer is a semi-transparent covering on an element that\n * indicates its state. State layers provide a systematic approach to\n * visualizing states by using opacity. A layer can be applied to an entire\n * element or in a circular shape and only one state layer can be applied at a\n * given time.\n *\n * @final\n * @suppress {visibility}\n */\nlet MdRipple = class MdRipple extends Ripple {\n};\nMdRipple.styles = [styles];\nMdRipple = __decorate([\n    customElement('md-ripple')\n], MdRipple);\nexport { MdRipple };\n//# sourceMappingURL=ripple.js.map","import{html as t,svg as r}from\"./lit-html.js\";\n/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const e=Symbol.for(\"\"),l=t=>{if((null==t?void 0:t.r)===e)return null==t?void 0:t._$litStatic$},o=t=>({_$litStatic$:t,r:e}),i=(t,...r)=>({_$litStatic$:r.reduce(((r,e,l)=>r+(t=>{if(void 0!==t._$litStatic$)return t._$litStatic$;throw Error(`Value passed to 'literal' function must be a 'literal' result: ${t}. Use 'unsafeStatic' to pass non-literal values, but\\n            take care to ensure page security.`)})(e)+t[l+1]),t[0]),r:e}),s=new Map,a=t=>(r,...e)=>{const o=e.length;let i,a;const n=[],u=[];let c,$=0,f=!1;for(;$<o;){for(c=r[$];$<o&&void 0!==(a=e[$],i=l(a));)c+=i+r[++$],f=!0;$!==o&&u.push(a),n.push(c),$++}if($===o&&n.push(r[o]),f){const t=n.join(\"$$lit$$\");void 0===(r=s.get(t))&&(n.raw=n,s.set(t,r=n)),e=u}return t(r,...e)},n=a(t),u=a(r);export{n as html,i as literal,u as svg,o as unsafeStatic,a as withStatic};\n//# sourceMappingURL=static.js.map\n","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * Accessibility Object Model reflective aria properties.\n */\nexport const ARIA_PROPERTIES = [\n    'ariaAtomic',\n    'ariaAutoComplete',\n    'ariaBusy',\n    'ariaChecked',\n    'ariaColCount',\n    'ariaColIndex',\n    'ariaColSpan',\n    'ariaCurrent',\n    'ariaDisabled',\n    'ariaExpanded',\n    'ariaHasPopup',\n    'ariaHidden',\n    'ariaInvalid',\n    'ariaKeyShortcuts',\n    'ariaLabel',\n    'ariaLevel',\n    'ariaLive',\n    'ariaModal',\n    'ariaMultiLine',\n    'ariaMultiSelectable',\n    'ariaOrientation',\n    'ariaPlaceholder',\n    'ariaPosInSet',\n    'ariaPressed',\n    'ariaReadOnly',\n    'ariaRequired',\n    'ariaRoleDescription',\n    'ariaRowCount',\n    'ariaRowIndex',\n    'ariaRowSpan',\n    'ariaSelected',\n    'ariaSetSize',\n    'ariaSort',\n    'ariaValueMax',\n    'ariaValueMin',\n    'ariaValueNow',\n    'ariaValueText',\n];\n/**\n * Accessibility Object Model aria attributes.\n */\nexport const ARIA_ATTRIBUTES = ARIA_PROPERTIES.map(ariaPropertyToAttribute);\n/**\n * Checks if an attribute is one of the AOM aria attributes.\n *\n * @example\n * isAriaAttribute('aria-label'); // true\n *\n * @param attribute The attribute to check.\n * @return True if the attribute is an aria attribute, or false if not.\n */\nexport function isAriaAttribute(attribute) {\n    return attribute.startsWith('aria-');\n}\n/**\n * Converts an AOM aria property into its corresponding attribute.\n *\n * @example\n * ariaPropertyToAttribute('ariaLabel'); // 'aria-label'\n *\n * @param property The aria property.\n * @return The aria attribute.\n */\nexport function ariaPropertyToAttribute(property) {\n    return property\n        .replace('aria', 'aria-')\n        // IDREF attributes also include an \"Element\" or \"Elements\" suffix\n        .replace(/Elements?/g, '')\n        .toLowerCase();\n}\n//# sourceMappingURL=aria.js.map","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { ARIA_PROPERTIES, ariaPropertyToAttribute } from './aria.js';\n/**\n * Sets up a `ReactiveElement` constructor to enable updates when delegating\n * aria attributes. Elements may bind `this.aria*` properties to `aria-*`\n * attributes in their render functions.\n *\n * This function will:\n * - Call `requestUpdate()` when an aria attribute changes.\n * - Add `role=\"presentation\"` to the host.\n *\n * NOTE: The following features are not currently supported:\n * - Delegating IDREF attributes (ex: `aria-labelledby`, `aria-controls`)\n * - Delegating the `role` attribute\n *\n * @example\n * class XButton extends LitElement {\n *   static {\n *     requestUpdateOnAriaChange(this);\n *   }\n *\n *   protected override render() {\n *     return html`\n *       <button aria-label=${this.ariaLabel || nothing}>\n *         <slot></slot>\n *       </button>\n *     `;\n *   }\n * }\n *\n * @param ctor The `ReactiveElement` constructor to patch.\n */\nexport function requestUpdateOnAriaChange(ctor) {\n    for (const ariaProperty of ARIA_PROPERTIES) {\n        ctor.createProperty(ariaProperty, {\n            attribute: ariaPropertyToAttribute(ariaProperty),\n            reflect: true,\n        });\n    }\n    ctor.addInitializer(element => {\n        const controller = {\n            hostConnected() {\n                element.setAttribute('role', 'presentation');\n            }\n        };\n        element.addController(controller);\n    });\n}\n//# sourceMappingURL=delegate.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * Re-dispatches an event from the provided element.\n *\n * This function is useful for forwarding non-composed events, such as `change`\n * events.\n *\n * @example\n * class MyInput extends LitElement {\n *   render() {\n *     return html`<input @change=${this.redispatchEvent}>`;\n *   }\n *\n *   protected redispatchEvent(event: Event) {\n *     redispatchEvent(this, event);\n *   }\n * }\n *\n * @param element The element to dispatch the event from.\n * @param event The event to re-dispatch.\n * @return Whether or not the event was dispatched (if cancelable).\n */\nexport function redispatchEvent(element, event) {\n    // For bubbling events in SSR light DOM (or composed), stop their propagation\n    // and dispatch the copy.\n    if (event.bubbles && (!element.shadowRoot || event.composed)) {\n        event.stopPropagation();\n    }\n    const copy = Reflect.construct(event.constructor, [event.type, event]);\n    const dispatched = element.dispatchEvent(copy);\n    if (!dispatched) {\n        event.preventDefault();\n    }\n    return dispatched;\n}\n/**\n * Dispatches a click event to the given element that triggers a native action,\n * but is not composed and therefore is not seen outside the element.\n *\n * This is useful for responding to an external click event on the host element\n * that should trigger an internal action like a button click.\n *\n * Note, a helper is provided because setting this up correctly is a bit tricky.\n * In particular, calling `click` on an element creates a composed event, which\n * is not desirable, and a manually dispatched event must specifically be a\n * `MouseEvent` to trigger a native action.\n *\n * @example\n * hostClickListener = (event: MouseEvent) {\n *   if (isActivationClick(event)) {\n *     this.dispatchActivationClick(this.buttonElement);\n *   }\n * }\n *\n */\nexport function dispatchActivationClick(element) {\n    const event = new MouseEvent('click', { bubbles: true });\n    element.dispatchEvent(event);\n    return event;\n}\n/**\n * Returns true if the click event should trigger an activation behavior. The\n * behavior is defined by the element and is whatever it should do when\n * clicked.\n *\n * Typically when an element needs to handle a click, the click is generated\n * from within the element and an event listener within the element implements\n * the needed behavior; however, it's possible to fire a click directly\n * at the element that the element should handle. This method helps\n * distinguish these \"external\" clicks.\n *\n * An \"external\" click can be triggered in a number of ways: via a click\n * on an associated label for a form  associated element, calling\n * `element.click()`, or calling\n * `element.dispatchEvent(new MouseEvent('click', ...))`.\n *\n * Also works around Firefox issue\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1804576 by squelching\n * events for a microtask after called.\n *\n * @example\n * hostClickListener = (event: MouseEvent) {\n *   if (isActivationClick(event)) {\n *     this.dispatchActivationClick(this.buttonElement);\n *   }\n * }\n *\n */\nexport function isActivationClick(event) {\n    // Event must start at the event target.\n    if (event.currentTarget !== event.target) {\n        return false;\n    }\n    // Event must not be retargeted from shadowRoot.\n    if (event.composedPath()[0] !== event.target) {\n        return false;\n    }\n    // Target must not be disabled; this should only occur for a synthetically\n    // dispatched click.\n    if (event.target.disabled) {\n        return false;\n    }\n    // This is an activation if the event should not be squelched.\n    return !squelchEvent(event);\n}\n// TODO(https://bugzilla.mozilla.org/show_bug.cgi?id=1804576)\n//  Remove when Firefox bug is addressed.\nfunction squelchEvent(event) {\n    const squelched = isSquelchingEvents;\n    if (squelched) {\n        event.preventDefault();\n        event.stopImmediatePropagation();\n    }\n    squelchEventsForMicrotask();\n    return squelched;\n}\n// Ignore events for one microtask only.\nlet isSquelchingEvents = false;\nasync function squelchEventsForMicrotask() {\n    isSquelchingEvents = true;\n    // Need to pause for just one microtask.\n    // tslint:disable-next-line\n    await null;\n    isSquelchingEvents = false;\n}\n//# sourceMappingURL=events.js.map","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nvar _a;\nimport { __decorate } from \"tslib\";\nimport '../../focus/md-focus-ring.js';\nimport '../../ripple/ripple.js';\nimport { html, isServer, LitElement, nothing } from 'lit';\nimport { property, query, queryAssignedElements } from 'lit/decorators.js';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { html as staticHtml, literal } from 'lit/static-html.js';\nimport { requestUpdateOnAriaChange } from '../../internal/aria/delegate.js';\nimport { dispatchActivationClick, isActivationClick, redispatchEvent } from '../../internal/controller/events.js';\n/**\n * A button component.\n */\nexport class Button extends LitElement {\n    /** @nocollapse */\n    static get formAssociated() {\n        return true;\n    }\n    constructor() {\n        super();\n        /**\n         * Whether or not the button is disabled.\n         */\n        this.disabled = false;\n        /**\n         * Whether to render the icon at the inline end of the label rather than the\n         * inline start.\n         *\n         * _Note:_ Link buttons cannot have trailing icons.\n         */\n        this.trailingIcon = false;\n        /**\n         * Whether to display the icon or not.\n         */\n        this.hasIcon = false;\n        /**\n         * Specifies the type of button, used for controlling forms. When type\n         * is `submit`, the containing form is submitted; when it is `reset` the\n         * form is reset.\n         */\n        this.type = '';\n        this.internals = this /* needed for closure */.attachInternals();\n        // flag to avoid processing redispatched event.\n        this.isRedispatchingEvent = false;\n        this.handleActivationClick = (event) => {\n            if (!isActivationClick((event)) || !this.buttonElement) {\n                return;\n            }\n            this.focus();\n            dispatchActivationClick(this.buttonElement);\n        };\n        if (!isServer) {\n            this.addEventListener('click', this.handleActivationClick);\n        }\n    }\n    focus() {\n        this.buttonElement?.focus();\n    }\n    blur() {\n        this.buttonElement?.blur();\n    }\n    render() {\n        // Link buttons may not be disabled\n        const isDisabled = this.disabled && !this.href;\n        const button = this.href ? literal `a` : literal `button`;\n        // Needed for closure conformance\n        const { ariaLabel, ariaHasPopup, ariaExpanded } = this;\n        return staticHtml `\n      <${button}\n        class=\"button ${classMap(this.getRenderClasses())}\"\n        ?disabled=${isDisabled}\n        aria-label=\"${ariaLabel || nothing}\"\n        aria-haspopup=\"${ariaHasPopup || nothing}\"\n        aria-expanded=\"${ariaExpanded || nothing}\"\n        href=${this.href || nothing}\n        target=${this.target || nothing}\n        @click=\"${this.handleClick}\"\n      >\n        ${this.renderFocusRing()}\n        ${this.renderElevation()}\n        ${this.renderRipple()}\n        ${this.renderOutline()}\n        ${this.renderTouchTarget()}\n        ${this.renderLeadingIcon()}\n        ${this.renderLabel()}\n        ${this.renderTrailingIcon()}\n      </${button}>`;\n    }\n    getRenderClasses() {\n        return {\n            'button--icon-leading': !this.trailingIcon && this.hasIcon,\n            'button--icon-trailing': this.trailingIcon && this.hasIcon,\n        };\n    }\n    renderElevation() {\n        return nothing;\n    }\n    renderOutline() {\n        return nothing;\n    }\n    renderTouchTarget() {\n        return html `\n      <span class=\"button__touch\"></span>\n    `;\n    }\n    renderRipple() {\n        return html `<md-ripple class=\"button__ripple\" ?disabled=\"${this.disabled}\"></md-ripple>`;\n    }\n    renderFocusRing() {\n        return html `<md-focus-ring part=\"focus-ring\"></md-focus-ring>`;\n    }\n    renderLabel() {\n        return html `<span class=\"button__label\"><slot></slot></span>`;\n    }\n    renderLeadingIcon() {\n        return this.trailingIcon ? nothing : this.renderIcon();\n    }\n    renderTrailingIcon() {\n        return this.trailingIcon ? this.renderIcon() : nothing;\n    }\n    renderIcon() {\n        return html `<slot name=\"icon\" @slotchange=\"${this.handleSlotChange}\"></slot>`;\n    }\n    handleClick(event) {\n        if (this.isRedispatchingEvent) {\n            return;\n        }\n        // based on type, trigger form action.\n        const { type, internals: { form } } = this;\n        if (!form) {\n            return;\n        }\n        const isSubmit = type === 'submit', isReset = type === 'reset';\n        if (!(isSubmit || isReset)) {\n            return;\n        }\n        event.stopPropagation();\n        this.isRedispatchingEvent = true;\n        const prevented = !redispatchEvent(this, event);\n        this.isRedispatchingEvent = false;\n        if (prevented) {\n            return;\n        }\n        if (isSubmit) {\n            form.requestSubmit();\n        }\n        else if (isReset) {\n            form.reset();\n        }\n    }\n    handleSlotChange() {\n        this.hasIcon = this.assignedIcons.length > 0;\n    }\n}\n_a = Button;\n(() => {\n    requestUpdateOnAriaChange(_a);\n})();\n/** @nocollapse */\nButton.shadowRootOptions = { mode: 'open', delegatesFocus: true };\n__decorate([\n    property({ type: Boolean, reflect: true })\n], Button.prototype, \"disabled\", void 0);\n__decorate([\n    property()\n], Button.prototype, \"href\", void 0);\n__decorate([\n    property()\n], Button.prototype, \"target\", void 0);\n__decorate([\n    property({ type: Boolean, attribute: 'trailing-icon' })\n], Button.prototype, \"trailingIcon\", void 0);\n__decorate([\n    property({ type: Boolean, attribute: 'has-icon' })\n], Button.prototype, \"hasIcon\", void 0);\n__decorate([\n    property()\n], Button.prototype, \"type\", void 0);\n__decorate([\n    query('.button')\n], Button.prototype, \"buttonElement\", void 0);\n__decorate([\n    queryAssignedElements({ slot: 'icon', flatten: true })\n], Button.prototype, \"assignedIcons\", void 0);\n//# sourceMappingURL=button.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport '../../elevation/elevation.js';\nimport { html } from 'lit';\nimport { Button } from './button.js';\n/**\n * A filled button component.\n */\nexport class FilledButton extends Button {\n    renderElevation() {\n        return html `<md-elevation></md-elevation>`;\n    }\n}\n//# sourceMappingURL=filled-button.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_container-color: var(--md-filled-button-container-color, var(--md-sys-color-primary, #6750a4));--_container-elevation: var(--md-filled-button-container-elevation, 0);--_container-height: var(--md-filled-button-container-height, 40px);--_container-shadow-color: var(--md-filled-button-container-shadow-color, var(--md-sys-color-shadow, #000));--_container-shape: var(--md-filled-button-container-shape, 9999px);--_disabled-container-color: var(--md-filled-button-disabled-container-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-container-elevation: var(--md-filled-button-disabled-container-elevation, 0);--_disabled-container-opacity: var(--md-filled-button-disabled-container-opacity, 0.12);--_disabled-label-text-color: var(--md-filled-button-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-filled-button-disabled-label-text-opacity, 0.38);--_focus-container-elevation: var(--md-filled-button-focus-container-elevation, 0);--_focus-label-text-color: var(--md-filled-button-focus-label-text-color, var(--md-sys-color-on-primary, #fff));--_hover-container-elevation: var(--md-filled-button-hover-container-elevation, 1);--_hover-label-text-color: var(--md-filled-button-hover-label-text-color, var(--md-sys-color-on-primary, #fff));--_hover-state-layer-color: var(--md-filled-button-hover-state-layer-color, var(--md-sys-color-on-primary, #fff));--_hover-state-layer-opacity: var(--md-filled-button-hover-state-layer-opacity, 0.08);--_label-text-color: var(--md-filled-button-label-text-color, var(--md-sys-color-on-primary, #fff));--_label-text-type: var(--md-filled-button-label-text-type, var(--md-sys-typescale-label-large, 500 0.875rem / 1.25rem var(--md-ref-typeface-plain, Roboto)));--_pressed-container-elevation: var(--md-filled-button-pressed-container-elevation, 0);--_pressed-label-text-color: var(--md-filled-button-pressed-label-text-color, var(--md-sys-color-on-primary, #fff));--_pressed-state-layer-color: var(--md-filled-button-pressed-state-layer-color, var(--md-sys-color-on-primary, #fff));--_pressed-state-layer-opacity: var(--md-filled-button-pressed-state-layer-opacity, 0.12);--_disabled-icon-color: var(--md-filled-button-disabled-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-icon-opacity: var(--md-filled-button-disabled-icon-opacity, 0.38);--_focus-icon-color: var(--md-filled-button-focus-icon-color, var(--md-sys-color-on-primary, #fff));--_hover-icon-color: var(--md-filled-button-hover-icon-color, var(--md-sys-color-on-primary, #fff));--_icon-color: var(--md-filled-button-icon-color, var(--md-sys-color-on-primary, #fff));--_icon-size: var(--md-filled-button-icon-size, 18px);--_pressed-icon-color: var(--md-filled-button-pressed-icon-color, var(--md-sys-color-on-primary, #fff));--_spacing-leading: var(--md-filled-button-spacing-leading, 24px);--_spacing-trailing: var(--md-filled-button-spacing-trailing, 24px);--_with-icon-spacing-leading: var(--md-filled-button-with-icon-spacing-leading, 16px);--_with-icon-spacing-trailing: var(--md-filled-button-with-icon-spacing-trailing, 24px);--_with-trailing-icon-spacing-leading: var(--md-filled-button-with-trailing-icon-spacing-leading, 24px);--_with-trailing-icon-spacing-trailing: var(--md-filled-button-with-trailing-icon-spacing-trailing, 16px);--_container-shape-start-start: var( --md-filled-button-container-shape-start-start, var(--_container-shape) );--_container-shape-start-end: var( --md-filled-button-container-shape-start-end, var(--_container-shape) );--_container-shape-end-end: var( --md-filled-button-container-shape-end-end, var(--_container-shape) );--_container-shape-end-start: var( --md-filled-button-container-shape-end-start, var(--_container-shape) )}/*# sourceMappingURL=filled-styles.css.map */\n`;\n//# sourceMappingURL=filled-styles.css.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `md-elevation{transition-duration:280ms}.button{--md-elevation-level:var(--_container-elevation);--md-elevation-shadow-color:var(--_container-shadow-color)}.button:focus{--md-elevation-level:var(--_focus-container-elevation)}.button:hover{--md-elevation-level:var(--_hover-container-elevation)}.button:active{--md-elevation-level:var(--_pressed-container-elevation)}.button:disabled{--md-elevation-level:var(--_disabled-container-elevation)}/*# sourceMappingURL=shared-elevation-styles.css.map */\n`;\n//# sourceMappingURL=shared-elevation-styles.css.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{display:inline-flex;outline:none;-webkit-tap-highlight-color:rgba(0,0,0,0);vertical-align:top;--md-ripple-hover-color: var(--_hover-state-layer-color);--md-ripple-pressed-color: var(--_pressed-state-layer-color);--md-ripple-hover-opacity: var(--_hover-state-layer-opacity);--md-ripple-pressed-opacity: var(--_pressed-state-layer-opacity)}md-focus-ring{--md-focus-ring-shape-start-start: var(--_container-shape-start-start);--md-focus-ring-shape-start-end: var(--_container-shape-start-end);--md-focus-ring-shape-end-end: var(--_container-shape-end-end);--md-focus-ring-shape-end-start: var(--_container-shape-end-start)}:host([disabled]){cursor:default;pointer-events:none}.button{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;min-inline-size:64px;border:none;outline:none;user-select:none;-webkit-appearance:none;vertical-align:middle;background:rgba(0,0,0,0);text-decoration:none;inline-size:100%;position:relative;z-index:0;block-size:var(--_container-height);font:var(--_label-text-type);color:var(--_label-text-color);padding-inline-start:var(--_spacing-leading);padding-inline-end:var(--_spacing-trailing);gap:8px}.button::before{background-color:var(--_container-color);border-radius:inherit;content:\"\";inset:0;position:absolute}.button::-moz-focus-inner{padding:0;border:0}.button:hover{color:var(--_hover-label-text-color);cursor:pointer}.button:focus{color:var(--_focus-label-text-color)}.button:active{color:var(--_pressed-label-text-color);outline:none}.button:disabled .button__label{color:var(--_disabled-label-text-color);opacity:var(--_disabled-label-text-opacity)}.button:disabled::before{background-color:var(--_disabled-container-color);opacity:var(--_disabled-container-opacity)}@media(forced-colors: active){.button::before{content:\"\";box-sizing:border-box;border:1px solid rgba(0,0,0,0);border-radius:inherit;inset:0;pointer-events:none;position:absolute}}.button,.button__ripple{border-start-start-radius:var(--_container-shape-start-start);border-start-end-radius:var(--_container-shape-start-end);border-end-start-radius:var(--_container-shape-end-start);border-end-end-radius:var(--_container-shape-end-end)}.button::after,.button::before,md-elevation,.button__ripple{z-index:-1}.button--icon-leading{padding-inline-start:var(--_with-icon-spacing-leading);padding-inline-end:var(--_with-icon-spacing-trailing)}.button--icon-trailing{padding-inline-start:var(--_with-trailing-icon-spacing-leading);padding-inline-end:var(--_with-trailing-icon-spacing-trailing)}.link-button-wrapper{inline-size:100%}.button ::slotted([slot=icon]){display:inline-flex;position:relative;writing-mode:horizontal-tb;fill:currentColor;color:var(--_icon-color);font-size:var(--_icon-size);inline-size:var(--_icon-size);block-size:var(--_icon-size)}.button:hover ::slotted([slot=icon]){color:var(--_hover-icon-color)}.button:focus ::slotted([slot=icon]){color:var(--_focus-icon-color)}.button:active ::slotted([slot=icon]){color:var(--_pressed-icon-color)}.button:disabled ::slotted([slot=icon]){color:var(--_disabled-icon-color);opacity:var(--_disabled-icon-opacity)}.button__touch{position:absolute;top:50%;height:48px;left:0;right:0;transform:translateY(-50%)}/*# sourceMappingURL=shared-styles.css.map */\n`;\n//# sourceMappingURL=shared-styles.css.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { FilledButton } from './internal/filled-button.js';\nimport { styles as filledStyles } from './internal/filled-styles.css.js';\nimport { styles as sharedElevationStyles } from './internal/shared-elevation-styles.css.js';\nimport { styles as sharedStyles } from './internal/shared-styles.css.js';\n/**\n * @summary Buttons help people take action, such as sending an email, sharing a\n * document, or liking a comment.\n *\n * @description\n * __Emphasis:__ High emphasis – For the primary, most important, or most common\n * action on a screen\n *\n * __Rationale:__ The filled button’s contrasting surface color makes it the\n * most prominent button after the FAB. It’s used for final or unblocking\n * actions in a flow.\n *\n * __Example usages:__\n * - Save\n * - Confirm\n * - Done\n *\n * @final\n * @suppress {visibility}\n */\nlet MdFilledButton = class MdFilledButton extends FilledButton {\n};\nMdFilledButton.styles = [sharedStyles, sharedElevationStyles, filledStyles];\nMdFilledButton = __decorate([\n    customElement('md-filled-button')\n], MdFilledButton);\nexport { MdFilledButton };\n//# sourceMappingURL=filled-button.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { html } from 'lit';\nimport { Button } from './button.js';\n/**\n * An outlined button component.\n */\nexport class OutlinedButton extends Button {\n    renderOutline() {\n        return html `<span class=\"button__outline\"></span>`;\n    }\n}\n//# sourceMappingURL=outlined-button.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_container-height: var(--md-outlined-button-container-height, 40px);--_container-shape: var(--md-outlined-button-container-shape, 9999px);--_disabled-label-text-color: var(--md-outlined-button-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-outlined-button-disabled-label-text-opacity, 0.38);--_disabled-outline-color: var(--md-outlined-button-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-outline-opacity: var(--md-outlined-button-disabled-outline-opacity, 0.12);--_focus-label-text-color: var(--md-outlined-button-focus-label-text-color, var(--md-sys-color-primary, #6750a4));--_hover-label-text-color: var(--md-outlined-button-hover-label-text-color, var(--md-sys-color-primary, #6750a4));--_hover-state-layer-color: var(--md-outlined-button-hover-state-layer-color, var(--md-sys-color-primary, #6750a4));--_hover-state-layer-opacity: var(--md-outlined-button-hover-state-layer-opacity, 0.08);--_label-text-color: var(--md-outlined-button-label-text-color, var(--md-sys-color-primary, #6750a4));--_label-text-type: var(--md-outlined-button-label-text-type, var(--md-sys-typescale-label-large, 500 0.875rem / 1.25rem var(--md-ref-typeface-plain, Roboto)));--_outline-color: var(--md-outlined-button-outline-color, var(--md-sys-color-outline, #79747e));--_outline-width: var(--md-outlined-button-outline-width, 1px);--_pressed-label-text-color: var(--md-outlined-button-pressed-label-text-color, var(--md-sys-color-primary, #6750a4));--_pressed-outline-color: var(--md-outlined-button-pressed-outline-color, var(--md-sys-color-outline, #79747e));--_pressed-state-layer-color: var(--md-outlined-button-pressed-state-layer-color, var(--md-sys-color-primary, #6750a4));--_pressed-state-layer-opacity: var(--md-outlined-button-pressed-state-layer-opacity, 0.12);--_disabled-icon-color: var(--md-outlined-button-disabled-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-icon-opacity: var(--md-outlined-button-disabled-icon-opacity, 0.38);--_focus-icon-color: var(--md-outlined-button-focus-icon-color, var(--md-sys-color-primary, #6750a4));--_hover-icon-color: var(--md-outlined-button-hover-icon-color, var(--md-sys-color-primary, #6750a4));--_icon-color: var(--md-outlined-button-icon-color, var(--md-sys-color-primary, #6750a4));--_icon-size: var(--md-outlined-button-icon-size, 18px);--_pressed-icon-color: var(--md-outlined-button-pressed-icon-color, var(--md-sys-color-primary, #6750a4));--_spacing-leading: var(--md-outlined-button-spacing-leading, 24px);--_spacing-trailing: var(--md-outlined-button-spacing-trailing, 24px);--_with-icon-spacing-leading: var(--md-outlined-button-with-icon-spacing-leading, 16px);--_with-icon-spacing-trailing: var(--md-outlined-button-with-icon-spacing-trailing, 24px);--_with-trailing-icon-spacing-leading: var(--md-outlined-button-with-trailing-icon-spacing-leading, 24px);--_with-trailing-icon-spacing-trailing: var(--md-outlined-button-with-trailing-icon-spacing-trailing, 16px);--_container-color: none;--_disabled-container-color: none;--_disabled-container-opacity: 0;--_container-shape-start-start: var( --md-outlined-button-container-shape-start-start, var(--_container-shape) );--_container-shape-start-end: var( --md-outlined-button-container-shape-start-end, var(--_container-shape) );--_container-shape-end-end: var( --md-outlined-button-container-shape-end-end, var(--_container-shape) );--_container-shape-end-start: var( --md-outlined-button-container-shape-end-start, var(--_container-shape) )}.button__outline{inset:0;border-style:solid;position:absolute;box-sizing:border-box;border-color:var(--_outline-color);border-start-start-radius:var(--_container-shape-start-start);border-start-end-radius:var(--_container-shape-start-end);border-end-start-radius:var(--_container-shape-end-start);border-end-end-radius:var(--_container-shape-end-end)}.button:active .button__outline{border-color:var(--_pressed-outline-color)}.button:disabled .button__outline{border-color:var(--_disabled-outline-color);opacity:var(--_disabled-outline-opacity)}.button__outline,.button__ripple{border-width:var(--_outline-width)}.button__ripple{inline-size:calc(100% - 2*var(--_outline-width));block-size:calc(100% - 2*var(--_outline-width));border-style:solid;border-color:rgba(0,0,0,0)}/*# sourceMappingURL=outlined-styles.css.map */\n`;\n//# sourceMappingURL=outlined-styles.css.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { OutlinedButton } from './internal/outlined-button.js';\nimport { styles as outlinedStyles } from './internal/outlined-styles.css.js';\nimport { styles as sharedStyles } from './internal/shared-styles.css.js';\n/**\n * @summary Buttons help people take action, such as sending an email, sharing a\n * document, or liking a comment.\n *\n * @description\n * __Emphasis:__ Medium emphasis – For important actions that don’t distract\n * from other onscreen elements.\n *\n * __Rationale:__ Use an outlined button for actions that need attention but\n * aren’t the primary action, such as “See all” or “Add to cart.” This is also\n * the button to use for giving someone the opportunity to change their mind or\n * escape a flow.\n *\n * __Example usages:__\n * - Reply\n * - View all\n * - Add to cart\n * - Take out of trash\n *\n * @final\n * @suppress {visibility}\n */\nlet MdOutlinedButton = class MdOutlinedButton extends OutlinedButton {\n};\nMdOutlinedButton.styles = [sharedStyles, outlinedStyles];\nMdOutlinedButton = __decorate([\n    customElement('md-outlined-button')\n], MdOutlinedButton);\nexport { MdOutlinedButton };\n//# sourceMappingURL=outlined-button.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { Button } from './button.js';\n/**\n * A text button component.\n */\nexport class TextButton extends Button {\n}\n//# sourceMappingURL=text-button.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_container-height: var(--md-text-button-container-height, 40px);--_container-shape: var(--md-text-button-container-shape, 9999px);--_disabled-label-text-color: var(--md-text-button-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-text-button-disabled-label-text-opacity, 0.38);--_focus-label-text-color: var(--md-text-button-focus-label-text-color, var(--md-sys-color-primary, #6750a4));--_hover-label-text-color: var(--md-text-button-hover-label-text-color, var(--md-sys-color-primary, #6750a4));--_hover-state-layer-color: var(--md-text-button-hover-state-layer-color, var(--md-sys-color-primary, #6750a4));--_hover-state-layer-opacity: var(--md-text-button-hover-state-layer-opacity, 0.08);--_label-text-color: var(--md-text-button-label-text-color, var(--md-sys-color-primary, #6750a4));--_label-text-type: var(--md-text-button-label-text-type, var(--md-sys-typescale-label-large, 500 0.875rem / 1.25rem var(--md-ref-typeface-plain, Roboto)));--_pressed-label-text-color: var(--md-text-button-pressed-label-text-color, var(--md-sys-color-primary, #6750a4));--_pressed-state-layer-color: var(--md-text-button-pressed-state-layer-color, var(--md-sys-color-primary, #6750a4));--_pressed-state-layer-opacity: var(--md-text-button-pressed-state-layer-opacity, 0.12);--_disabled-icon-color: var(--md-text-button-disabled-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-icon-opacity: var(--md-text-button-disabled-icon-opacity, 0.38);--_focus-icon-color: var(--md-text-button-focus-icon-color, var(--md-sys-color-primary, #6750a4));--_hover-icon-color: var(--md-text-button-hover-icon-color, var(--md-sys-color-primary, #6750a4));--_icon-color: var(--md-text-button-icon-color, var(--md-sys-color-primary, #6750a4));--_icon-size: var(--md-text-button-icon-size, 18px);--_pressed-icon-color: var(--md-text-button-pressed-icon-color, var(--md-sys-color-primary, #6750a4));--_spacing-leading: var(--md-text-button-spacing-leading, 12px);--_spacing-trailing: var(--md-text-button-spacing-trailing, 12px);--_with-icon-spacing-leading: var(--md-text-button-with-icon-spacing-leading, 12px);--_with-icon-spacing-trailing: var(--md-text-button-with-icon-spacing-trailing, 16px);--_with-trailing-icon-spacing-leading: var(--md-text-button-with-trailing-icon-spacing-leading, 16px);--_with-trailing-icon-spacing-trailing: var(--md-text-button-with-trailing-icon-spacing-trailing, 12px);--_container-color: none;--_disabled-container-color: none;--_disabled-container-opacity: 0;--_container-shape-start-start: var( --md-text-button-container-shape-start-start, var(--_container-shape) );--_container-shape-start-end: var( --md-text-button-container-shape-start-end, var(--_container-shape) );--_container-shape-end-end: var( --md-text-button-container-shape-end-end, var(--_container-shape) );--_container-shape-end-start: var( --md-text-button-container-shape-end-start, var(--_container-shape) )}/*# sourceMappingURL=text-styles.css.map */\n`;\n//# sourceMappingURL=text-styles.css.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { styles as sharedStyles } from './internal/shared-styles.css.js';\nimport { TextButton } from './internal/text-button.js';\nimport { styles as textStyles } from './internal/text-styles.css.js';\n/**\n * @summary Buttons help people take action, such as sending an email, sharing a\n * document, or liking a comment.\n *\n * @description\n * __Emphasis:__ Low emphasis – For optional or supplementary actions with the\n * least amount of prominence\n *\n * __Rationale:__ Text buttons have less visual prominence, so should be used\n * for low emphasis actions, such as an alternative option.\n *\n * __Example usages:__\n * - Learn more\n * - View all\n * - Change account\n * - Turn on\n *\n * @final\n * @suppress {visibility}\n */\nlet MdTextButton = class MdTextButton extends TextButton {\n};\nMdTextButton.styles = [sharedStyles, textStyles];\nMdTextButton = __decorate([\n    customElement('md-text-button')\n], MdTextButton);\nexport { MdTextButton };\n//# sourceMappingURL=text-button.js.map","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nvar _a;\nimport { __decorate } from \"tslib\";\nimport '../../focus/md-focus-ring.js';\nimport '../../ripple/ripple.js';\nimport { html, isServer, LitElement, nothing } from 'lit';\nimport { property, query, state } from 'lit/decorators.js';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { requestUpdateOnAriaChange } from '../../internal/aria/delegate.js';\nimport { dispatchActivationClick, isActivationClick, redispatchEvent } from '../../internal/controller/events.js';\n/**\n * A checkbox component.\n */\nexport class Checkbox extends LitElement {\n    /**\n     * The HTML name to use in form submission.\n     */\n    get name() {\n        return this.getAttribute('name') ?? '';\n    }\n    set name(name) {\n        this.setAttribute('name', name);\n    }\n    /**\n     * The associated form element with which this element's value will submit.\n     */\n    get form() {\n        return this.internals.form;\n    }\n    /**\n     * The labels this element is associated with.\n     */\n    get labels() {\n        return this.internals.labels;\n    }\n    constructor() {\n        super();\n        /**\n         * Whether or not the checkbox is selected.\n         */\n        this.checked = false;\n        /**\n         * Whether or not the checkbox is disabled.\n         */\n        this.disabled = false;\n        /**\n         * Whether or not the checkbox is invalid.\n         */\n        this.error = false;\n        /**\n         * Whether or not the checkbox is indeterminate.\n         *\n         * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#indeterminate_state_checkboxes\n         */\n        this.indeterminate = false;\n        /**\n         * The value of the checkbox that is submitted with a form when selected.\n         *\n         * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#value\n         */\n        this.value = 'on';\n        this.prevChecked = false;\n        this.prevDisabled = false;\n        this.prevIndeterminate = false;\n        this.internals = this /* needed for closure */.attachInternals();\n        if (!isServer) {\n            this.addEventListener('click', (event) => {\n                if (!isActivationClick(event)) {\n                    return;\n                }\n                this.focus();\n                dispatchActivationClick(this.input);\n            });\n        }\n    }\n    focus() {\n        this.input?.focus();\n    }\n    update(changed) {\n        if (changed.has('checked') || changed.has('disabled') ||\n            changed.has('indeterminate')) {\n            this.prevChecked = changed.get('checked') ?? this.checked;\n            this.prevDisabled = changed.get('disabled') ?? this.disabled;\n            this.prevIndeterminate =\n                changed.get('indeterminate') ?? this.indeterminate;\n        }\n        const shouldAddFormValue = this.checked && !this.indeterminate;\n        const state = String(this.checked);\n        this.internals.setFormValue(shouldAddFormValue ? this.value : null, state);\n        super.update(changed);\n    }\n    render() {\n        const prevNone = !this.prevChecked && !this.prevIndeterminate;\n        const prevChecked = this.prevChecked && !this.prevIndeterminate;\n        const prevIndeterminate = this.prevIndeterminate;\n        const isChecked = this.checked && !this.indeterminate;\n        const isIndeterminate = this.indeterminate;\n        const containerClasses = classMap({\n            'disabled': this.disabled,\n            'selected': isChecked || isIndeterminate,\n            'unselected': !isChecked && !isIndeterminate,\n            'checked': isChecked,\n            'indeterminate': isIndeterminate,\n            'error': this.error && !this.disabled,\n            'prev-unselected': prevNone,\n            'prev-checked': prevChecked,\n            'prev-indeterminate': prevIndeterminate,\n            'prev-disabled': this.prevDisabled,\n        });\n        // Needed for closure conformance\n        const { ariaLabel } = this;\n        return html `\n      <div class=\"container ${containerClasses}\">\n        <div class=\"outline\"></div>\n        <div class=\"background\"></div>\n        <md-focus-ring part=\"focus-ring\" for=\"input\"></md-focus-ring>\n        <md-ripple for=\"input\" ?disabled=${this.disabled}></md-ripple>\n        <svg class=\"icon\" viewBox=\"0 0 18 18\" aria-hidden=\"true\">\n          <rect class=\"mark short\" />\n          <rect class=\"mark long\" />\n        </svg>\n\n        <input type=\"checkbox\"\n          id=\"input\"\n          aria-checked=${isIndeterminate ? 'mixed' : nothing}\n          aria-label=${ariaLabel || nothing}\n          aria-invalid=${this.error || nothing}\n          ?disabled=${this.disabled}\n          .indeterminate=${this.indeterminate}\n          .checked=${this.checked}\n          @change=${this.handleChange}\n        >\n      </div>\n    `;\n    }\n    handleChange(event) {\n        const target = event.target;\n        this.checked = target.checked;\n        this.indeterminate = target.indeterminate;\n        redispatchEvent(this, event);\n    }\n    /** @private */\n    formResetCallback() {\n        // The checked property does not reflect, so the original attribute set by\n        // the user is used to determine the default value.\n        this.checked = this.hasAttribute('checked');\n    }\n    /** @private */\n    formStateRestoreCallback(state) {\n        this.checked = state === 'true';\n    }\n}\n_a = Checkbox;\n(() => {\n    requestUpdateOnAriaChange(_a);\n})();\n/** @nocollapse */\nCheckbox.formAssociated = true;\n__decorate([\n    property({ type: Boolean })\n], Checkbox.prototype, \"checked\", void 0);\n__decorate([\n    property({ type: Boolean, reflect: true })\n], Checkbox.prototype, \"disabled\", void 0);\n__decorate([\n    property({ type: Boolean })\n], Checkbox.prototype, \"error\", void 0);\n__decorate([\n    property({ type: Boolean })\n], Checkbox.prototype, \"indeterminate\", void 0);\n__decorate([\n    property()\n], Checkbox.prototype, \"value\", void 0);\n__decorate([\n    state()\n], Checkbox.prototype, \"prevChecked\", void 0);\n__decorate([\n    state()\n], Checkbox.prototype, \"prevDisabled\", void 0);\n__decorate([\n    state()\n], Checkbox.prototype, \"prevIndeterminate\", void 0);\n__decorate([\n    query('input')\n], Checkbox.prototype, \"input\", void 0);\n//# sourceMappingURL=checkbox.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_container-shape: var(--md-checkbox-container-shape, 2px);--_container-size: var(--md-checkbox-container-size, 18px);--_error-hover-state-layer-color: var(--md-checkbox-error-hover-state-layer-color, var(--md-sys-color-error, #b3261e));--_error-hover-state-layer-opacity: var(--md-checkbox-error-hover-state-layer-opacity, 0.08);--_error-pressed-state-layer-color: var(--md-checkbox-error-pressed-state-layer-color, var(--md-sys-color-error, #b3261e));--_error-pressed-state-layer-opacity: var(--md-checkbox-error-pressed-state-layer-opacity, 0.12);--_icon-size: var(--md-checkbox-icon-size, 18px);--_selected-container-color: var(--md-checkbox-selected-container-color, var(--md-sys-color-primary, #6750a4));--_selected-disabled-container-color: var(--md-checkbox-selected-disabled-container-color, var(--md-sys-color-on-surface, #1d1b20));--_selected-disabled-container-opacity: var(--md-checkbox-selected-disabled-container-opacity, 0.38);--_selected-disabled-icon-color: var(--md-checkbox-selected-disabled-icon-color, var(--md-sys-color-surface, #fef7ff));--_selected-error-container-color: var(--md-checkbox-selected-error-container-color, var(--md-sys-color-error, #b3261e));--_selected-error-focus-container-color: var(--md-checkbox-selected-error-focus-container-color, var(--md-sys-color-error, #b3261e));--_selected-error-focus-icon-color: var(--md-checkbox-selected-error-focus-icon-color, var(--md-sys-color-on-error, #fff));--_selected-error-hover-container-color: var(--md-checkbox-selected-error-hover-container-color, var(--md-sys-color-error, #b3261e));--_selected-error-hover-icon-color: var(--md-checkbox-selected-error-hover-icon-color, var(--md-sys-color-on-error, #fff));--_selected-error-icon-color: var(--md-checkbox-selected-error-icon-color, var(--md-sys-color-on-error, #fff));--_selected-error-pressed-container-color: var(--md-checkbox-selected-error-pressed-container-color, var(--md-sys-color-error, #b3261e));--_selected-error-pressed-icon-color: var(--md-checkbox-selected-error-pressed-icon-color, var(--md-sys-color-on-error, #fff));--_selected-focus-container-color: var(--md-checkbox-selected-focus-container-color, var(--md-sys-color-primary, #6750a4));--_selected-focus-icon-color: var(--md-checkbox-selected-focus-icon-color, var(--md-sys-color-on-primary, #fff));--_selected-hover-container-color: var(--md-checkbox-selected-hover-container-color, var(--md-sys-color-primary, #6750a4));--_selected-hover-icon-color: var(--md-checkbox-selected-hover-icon-color, var(--md-sys-color-on-primary, #fff));--_selected-hover-state-layer-color: var(--md-checkbox-selected-hover-state-layer-color, var(--md-sys-color-primary, #6750a4));--_selected-hover-state-layer-opacity: var(--md-checkbox-selected-hover-state-layer-opacity, 0.08);--_selected-icon-color: var(--md-checkbox-selected-icon-color, var(--md-sys-color-on-primary, #fff));--_selected-pressed-container-color: var(--md-checkbox-selected-pressed-container-color, var(--md-sys-color-primary, #6750a4));--_selected-pressed-icon-color: var(--md-checkbox-selected-pressed-icon-color, var(--md-sys-color-on-primary, #fff));--_selected-pressed-state-layer-color: var(--md-checkbox-selected-pressed-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--_selected-pressed-state-layer-opacity: var(--md-checkbox-selected-pressed-state-layer-opacity, 0.12);--_state-layer-shape: var(--md-checkbox-state-layer-shape, 9999px);--_state-layer-size: var(--md-checkbox-state-layer-size, 40px);--_disabled-container-opacity: var(--md-checkbox-disabled-container-opacity, 0.38);--_disabled-outline-color: var(--md-checkbox-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-outline-width: var(--md-checkbox-disabled-outline-width, 2px);--_error-focus-outline-color: var(--md-checkbox-error-focus-outline-color, var(--md-sys-color-error, #b3261e));--_error-hover-outline-color: var(--md-checkbox-error-hover-outline-color, var(--md-sys-color-error, #b3261e));--_error-outline-color: var(--md-checkbox-error-outline-color, var(--md-sys-color-error, #b3261e));--_error-pressed-outline-color: var(--md-checkbox-error-pressed-outline-color, var(--md-sys-color-error, #b3261e));--_focus-outline-color: var(--md-checkbox-focus-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_focus-outline-width: var(--md-checkbox-focus-outline-width, 2px);--_hover-outline-color: var(--md-checkbox-hover-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-outline-width: var(--md-checkbox-hover-outline-width, 2px);--_hover-state-layer-color: var(--md-checkbox-hover-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-state-layer-opacity: var(--md-checkbox-hover-state-layer-opacity, 0.08);--_outline-color: var(--md-checkbox-outline-color, var(--md-sys-color-on-surface-variant, #49454f));--_outline-width: var(--md-checkbox-outline-width, 2px);--_pressed-outline-color: var(--md-checkbox-pressed-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_pressed-outline-width: var(--md-checkbox-pressed-outline-width, 2px);--_pressed-state-layer-color: var(--md-checkbox-pressed-state-layer-color, var(--md-sys-color-primary, #6750a4));--_pressed-state-layer-opacity: var(--md-checkbox-pressed-state-layer-opacity, 0.12);--_container-shape-start-start: var( --md-checkbox-container-shape-start-start, var(--_container-shape) );--_container-shape-start-end: var( --md-checkbox-container-shape-start-end, var(--_container-shape) );--_container-shape-end-end: var( --md-checkbox-container-shape-end-end, var(--_container-shape) );--_container-shape-end-start: var( --md-checkbox-container-shape-end-start, var(--_container-shape) );border-start-start-radius:var(--_container-shape-start-start);border-start-end-radius:var(--_container-shape-start-end);border-end-end-radius:var(--_container-shape-end-end);border-end-start-radius:var(--_container-shape-end-start);display:inline-flex;height:48px;position:relative;vertical-align:top;width:48px;-webkit-tap-highlight-color:rgba(0,0,0,0)}md-focus-ring{--md-focus-ring-outward-offset: -2px}input{appearance:none;inset:0;margin:0;outline:none;position:absolute;opacity:0;block-size:100%;inline-size:100%}.container{border-radius:inherit;height:100%;position:relative;width:100%}.outline,.background,md-ripple,.icon{inset:0;margin:auto;position:absolute}.outline,.background{border-radius:inherit;height:var(--_container-size);width:var(--_container-size)}.outline{border-color:var(--_outline-color);border-style:solid;border-width:var(--_outline-width);box-sizing:border-box}.background{background-color:var(--_selected-container-color)}.background,.icon{opacity:0;transition-duration:150ms,50ms;transition-property:transform,opacity;transition-timing-function:cubic-bezier(0.3, 0, 0.8, 0.15),linear;transform:scale(0.6)}:where(.selected) :is(.background,.icon){opacity:1;transition-duration:350ms,50ms;transition-timing-function:cubic-bezier(0.05, 0.7, 0.1, 1),linear;transform:scale(1)}md-ripple{border-radius:var(--_state-layer-shape);height:var(--_state-layer-size);width:var(--_state-layer-size);--md-ripple-hover-color: var(--_hover-state-layer-color);--md-ripple-hover-opacity: var(--_hover-state-layer-opacity);--md-ripple-pressed-color: var(--_pressed-state-layer-color);--md-ripple-pressed-opacity: var(--_pressed-state-layer-opacity)}.selected md-ripple{--md-ripple-hover-color: var(--_selected-hover-state-layer-color);--md-ripple-hover-opacity: var(--_selected-hover-state-layer-opacity);--md-ripple-pressed-color: var(--_selected-pressed-state-layer-color);--md-ripple-pressed-opacity: var(--_selected-pressed-state-layer-opacity)}.error md-ripple{--md-ripple-hover-color: var(--_error-hover-state-layer-color);--md-ripple-hover-opacity: var(--_error-hover-state-layer-opacity);--md-ripple-pressed-color: var(--_error-pressed-state-layer-color);--md-ripple-pressed-opacity: var(--_error-pressed-state-layer-opacity)}.icon{fill:var(--_selected-icon-color);height:var(--_icon-size);width:var(--_icon-size)}.mark.short{height:2px;transition-property:transform,height;width:2px}.mark.long{height:2px;transition-property:transform,width;width:10px}.mark{animation-duration:150ms;animation-timing-function:cubic-bezier(0.3, 0, 0.8, 0.15);transition-duration:150ms;transition-timing-function:cubic-bezier(0.3, 0, 0.8, 0.15)}.selected .mark{animation-duration:350ms;animation-timing-function:cubic-bezier(0.05, 0.7, 0.1, 1);transition-duration:350ms;transition-timing-function:cubic-bezier(0.05, 0.7, 0.1, 1)}.checked .mark,.prev-checked.unselected .mark{transform:scaleY(-1) translate(7px, -14px) rotate(45deg)}.checked .mark.short,.prev-checked.unselected .mark.short{height:5.6568542495px}.checked .mark.long,.prev-checked.unselected .mark.long{width:11.313708499px}.indeterminate .mark,.prev-indeterminate.unselected .mark{transform:scaleY(-1) translate(4px, -10px) rotate(0deg)}.prev-unselected .mark{transition-property:none}.prev-unselected.checked .mark.long{animation-name:prev-unselected-to-checked}@keyframes prev-unselected-to-checked{from{width:0}}:where(.error) .outline{border-color:var(--_error-outline-color)}:where(.error) .background{background:var(--_selected-error-container-color)}:where(.error) .icon{fill:var(--_selected-error-icon-color)}:where(:hover) .outline{border-color:var(--_hover-outline-color);border-width:var(--_hover-outline-width)}:where(:hover) .background{background:var(--_selected-hover-container-color)}:where(:hover) .icon{fill:var(--_selected-hover-icon-color)}:where(.error:hover) .outline{border-color:var(--_error-hover-outline-color)}:where(.error:hover) .background{background:var(--_selected-error-hover-container-color)}:where(.error:hover) .icon{fill:var(--_selected-error-hover-icon-color)}:where(:focus-within) .outline{border-color:var(--_focus-outline-color);border-width:var(--_focus-outline-width)}:where(:focus-within) .background{background:var(--_selected-focus-container-color)}:where(:focus-within) .icon{fill:var(--_selected-focus-icon-color)}:where(.error:focus-within) .outline{border-color:var(--_error-focus-outline-color)}:where(.error:focus-within) .background{background:var(--_selected-error-focus-container-color)}:where(.error:focus-within) .icon{fill:var(--_selected-error-focus-icon-color)}:where(:active) .outline{border-color:var(--_pressed-outline-color);border-width:var(--_pressed-outline-width)}:where(:active) .background{background:var(--_selected-pressed-container-color)}:where(:active) .icon{fill:var(--_selected-pressed-icon-color)}:where(.error:active) .outline{border-color:var(--_error-pressed-outline-color)}:where(.error:active) .background{background:var(--_selected-error-pressed-container-color)}:where(.error:active) .icon{fill:var(--_selected-error-pressed-icon-color)}:where(.disabled,.prev-disabled) :is(.background,.icon,.mark){animation-duration:0s;transition-duration:0s}:where(.disabled) .outline{border-color:var(--_disabled-outline-color);border-width:var(--_disabled-outline-width);opacity:var(--_disabled-container-opacity)}:where(.selected.disabled) .outline{visibility:hidden}:where(.selected.disabled) .background{background:var(--_selected-disabled-container-color);opacity:var(--_selected-disabled-container-opacity)}:where(.disabled) .icon{fill:var(--_selected-disabled-icon-color)}@media(forced-colors: active){.background{background-color:CanvasText}.selected.disabled .background{background-color:GrayText;opacity:1}.outline{border-color:CanvasText}.disabled .outline{border-color:GrayText;opacity:1}.icon{fill:Canvas}}/*# sourceMappingURL=checkbox-styles.css.map */\n`;\n//# sourceMappingURL=checkbox-styles.css.js.map","/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { Checkbox } from './internal/checkbox.js';\nimport { styles } from './internal/checkbox-styles.css.js';\n/**\n * @summary Checkboxes allow users to select one or more items from a set.\n * Checkboxes can turn an option on or off.\n *\n * @description\n * Use checkboxes to:\n * - Select one or more options from a list\n * - Present a list containing sub-selections\n * - Turn an item on or off in a desktop environment\n *\n * @final\n * @suppress {visibility}\n */\nlet MdCheckbox = class MdCheckbox extends Checkbox {\n};\nMdCheckbox.styles = [styles];\nMdCheckbox = __decorate([\n    customElement('md-checkbox')\n], MdCheckbox);\nexport { MdCheckbox };\n//# sourceMappingURL=checkbox.js.map","/**\n * @license\n * Copyright 2022 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { html, LitElement } from 'lit';\n/**\n * TODO(b/265336902): add docs\n */\nexport class Icon extends LitElement {\n    render() {\n        return html `<slot></slot>`;\n    }\n}\n//# sourceMappingURL=icon.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_color: var(--md-icon-color, inherit);--_font: var(--md-icon-font, \"Material Symbols Outlined\");--_font-variation-settings: var(--md-icon-font-variation-settings, inherit);--_size: var(--md-icon-size, 24px);--_weight: var(--md-icon-weight, 400);display:inline-flex;color:var(--_color);font-family:var(--_font);font-weight:var(--_weight);font-style:normal;font-size:var(--_size);font-variation-settings:var(--_font-variation-settings);line-height:1;overflow:hidden;letter-spacing:normal;text-transform:none;white-space:nowrap;word-wrap:normal;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility;-moz-osx-font-smoothing:grayscale}::slotted(svg){fill:currentColor}::slotted(*){height:var(--_size);width:var(--_size)}/*# sourceMappingURL=icon-styles.css.map */\n`;\n//# sourceMappingURL=icon-styles.css.js.map","/**\n * @license\n * Copyright 2022 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { Icon } from './internal/icon.js';\nimport { styles } from './internal/icon-styles.css.js';\n/**\n * @final\n * @suppress {visibility}\n */\nlet MdIcon = class MdIcon extends Icon {\n};\n/** @nocollapse */\nMdIcon.styles = [styles];\nMdIcon = __decorate([\n    customElement('md-icon')\n], MdIcon);\nexport { MdIcon };\n//# sourceMappingURL=icon.js.map","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nvar _a;\nimport { __decorate } from \"tslib\";\nimport { html, LitElement, nothing } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { requestUpdateOnAriaChange } from '../../internal/aria/delegate.js';\n/**\n * A progress component.\n */\nexport class Progress extends LitElement {\n    constructor() {\n        super(...arguments);\n        /**\n         * Progress to display, a fraction between 0 and `max`.\n         */\n        this.value = 0;\n        /**\n         * Maximum progress to display, defaults to 1.\n         */\n        this.max = 1;\n        /**\n         * Whether or not to display indeterminate progress, which gives no indication\n         * to how long an activity will take.\n         */\n        this.indeterminate = false;\n        /**\n         * Whether or not to render indeterminate mode using 4 colors instead of one.\n         */\n        this.fourColor = false;\n    }\n    render() {\n        // Needed for closure conformance\n        const { ariaLabel } = this;\n        return html `\n      <div class=\"progress ${classMap(this.getRenderClasses())}\"\n        role=\"progressbar\"\n        aria-label=\"${ariaLabel || nothing}\"\n        aria-valuemin=\"0\"\n        aria-valuemax=${this.max}\n        aria-valuenow=${this.indeterminate ? nothing : this.value}\n      >${this.renderIndicator()}</div>\n    `;\n    }\n    getRenderClasses() {\n        return {\n            'indeterminate': this.indeterminate,\n            'four-color': this.fourColor,\n        };\n    }\n}\n_a = Progress;\n(() => {\n    requestUpdateOnAriaChange(_a);\n})();\n__decorate([\n    property({ type: Number })\n], Progress.prototype, \"value\", void 0);\n__decorate([\n    property({ type: Number })\n], Progress.prototype, \"max\", void 0);\n__decorate([\n    property({ type: Boolean })\n], Progress.prototype, \"indeterminate\", void 0);\n__decorate([\n    property({ type: Boolean, attribute: 'four-color' })\n], Progress.prototype, \"fourColor\", void 0);\n//# sourceMappingURL=progress.js.map","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { html } from 'lit';\nimport { Progress } from './progress.js';\n/**\n * A circular progress component.\n */\nexport class CircularProgress extends Progress {\n    renderIndicator() {\n        if (this.indeterminate) {\n            return this.renderIndeterminateContainer();\n        }\n        return this.renderDeterminateContainer();\n    }\n    // Determinate mode is rendered with an svg so the progress arc can be\n    // easily animated via stroke-dashoffset.\n    renderDeterminateContainer() {\n        const dashOffset = (1 - this.value / this.max) * 100;\n        // note, dash-array/offset are relative to Setting `pathLength` but\n        // Chrome seems to render this inaccurately and using a large viewbox helps.\n        return html `\n      <svg viewBox=\"0 0 4800 4800\">\n        <circle class=\"track\" pathLength=\"100\"></circle>\n        <circle class=\"progress\" pathLength=\"100\"\n          stroke-dashoffset=${dashOffset}></circle>\n      </svg>\n    `;\n    }\n    // Indeterminate mode rendered with 2 bordered-divs. The borders are\n    // clipped into half circles by their containers. The divs are then carefully\n    // animated to produce changes to the spinner arc size.\n    // This approach has 4.5x the FPS of rendering via svg on Chrome 111.\n    // See https://lit.dev/playground/#gist=febb773565272f75408ab06a0eb49746.\n    renderIndeterminateContainer() {\n        return html `\n      <div class=\"spinner\">\n        <div class=\"left\">\n          <div class=\"circle\"></div>\n        </div>\n        <div class=\"right\">\n          <div class=\"circle\"></div>\n        </div>\n      </div>`;\n    }\n}\n//# sourceMappingURL=circular-progress.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_active-indicator-color: var(--md-circular-progress-active-indicator-color, var(--md-sys-color-primary, #6750a4));--_active-indicator-width: var(--md-circular-progress-active-indicator-width, 8.3333333333);--_four-color-active-indicator-four-color: var(--md-circular-progress-four-color-active-indicator-four-color, var(--md-sys-color-tertiary-container, #ffd8e4));--_four-color-active-indicator-one-color: var(--md-circular-progress-four-color-active-indicator-one-color, var(--md-sys-color-primary, #6750a4));--_four-color-active-indicator-three-color: var(--md-circular-progress-four-color-active-indicator-three-color, var(--md-sys-color-tertiary, #7d5260));--_four-color-active-indicator-two-color: var(--md-circular-progress-four-color-active-indicator-two-color, var(--md-sys-color-primary-container, #eaddff));--_size: var(--md-circular-progress-size, 48px);display:inline-flex;vertical-align:middle;min-block-size:var(--_size);min-inline-size:var(--_size);position:relative;align-items:center;justify-content:center;contain:strict;content-visibility:auto}.progress{flex:1;align-self:stretch;margin:4px}.progress,.spinner,.left,.right,.circle,svg,.track,.progress{position:absolute;inset:0}svg{transform:rotate(-90deg)}circle{cx:50%;cy:50%;r:calc(50%*(1 - var(--_active-indicator-width)/100));stroke-width:calc(var(--_active-indicator-width)*1%);stroke-dasharray:100;fill:rgba(0,0,0,0)}.progress{transition:stroke-dashoffset 500ms cubic-bezier(0, 0, 0.2, 1);stroke:var(--_active-indicator-color)}.track{stroke:rgba(0,0,0,0)}.progress.indeterminate{animation:linear infinite linear-rotate;animation-duration:1568.2352941176ms}.spinner{animation:infinite both rotate-arc;animation-duration:5332ms;animation-timing-function:cubic-bezier(0.4, 0, 0.2, 1)}.left{overflow:hidden;inset:0 50% 0 0}.right{overflow:hidden;inset:0 0 0 50%}.circle{box-sizing:border-box;border-radius:50%;border:solid calc(var(--_active-indicator-width)/100*(var(--_size) - 8px));border-color:var(--_active-indicator-color) var(--_active-indicator-color) rgba(0,0,0,0) rgba(0,0,0,0);animation:expand-arc;animation-iteration-count:infinite;animation-fill-mode:both;animation-duration:1333ms,5332ms;animation-timing-function:cubic-bezier(0.4, 0, 0.2, 1)}.four-color .circle{animation-name:expand-arc,four-color}.left .circle{rotate:135deg;inset:0 -100% 0 0}.right .circle{rotate:100deg;inset:0 0 0 -100%;animation-delay:-666.5ms,0ms}@media screen and (forced-colors: active){.progress{stroke:CanvasText}.circle{border-color:CanvasText CanvasText Canvas Canvas}}@keyframes expand-arc{0%{transform:rotate(265deg)}50%{transform:rotate(130deg)}100%{transform:rotate(265deg)}}@keyframes rotate-arc{12.5%{transform:rotate(135deg)}25%{transform:rotate(270deg)}37.5%{transform:rotate(405deg)}50%{transform:rotate(540deg)}62.5%{transform:rotate(675deg)}75%{transform:rotate(810deg)}87.5%{transform:rotate(945deg)}100%{transform:rotate(1080deg)}}@keyframes linear-rotate{to{transform:rotate(360deg)}}@keyframes four-color{0%{border-top-color:var(--_four-color-active-indicator-one-color);border-right-color:var(--_four-color-active-indicator-one-color)}15%{border-top-color:var(--_four-color-active-indicator-one-color);border-right-color:var(--_four-color-active-indicator-one-color)}25%{border-top-color:var(--_four-color-active-indicator-two-color);border-right-color:var(--_four-color-active-indicator-two-color)}40%{border-top-color:var(--_four-color-active-indicator-two-color);border-right-color:var(--_four-color-active-indicator-two-color)}50%{border-top-color:var(--_four-color-active-indicator-three-color);border-right-color:var(--_four-color-active-indicator-three-color)}65%{border-top-color:var(--_four-color-active-indicator-three-color);border-right-color:var(--_four-color-active-indicator-three-color)}75%{border-top-color:var(--_four-color-active-indicator-four-color);border-right-color:var(--_four-color-active-indicator-four-color)}90%{border-top-color:var(--_four-color-active-indicator-four-color);border-right-color:var(--_four-color-active-indicator-four-color)}100%{border-top-color:var(--_four-color-active-indicator-one-color);border-right-color:var(--_four-color-active-indicator-one-color)}}/*# sourceMappingURL=circular-progress-styles.css.map */\n`;\n//# sourceMappingURL=circular-progress-styles.css.js.map","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { CircularProgress } from './internal/circular-progress.js';\nimport { styles } from './internal/circular-progress-styles.css.js';\n/**\n * @summary Circular progress indicators display progress by animating along an\n * invisible circular track in a clockwise direction. They can be applied\n * directly to a surface, such as a button or card.\n *\n * @description\n * Progress indicators inform users about the status of ongoing processes.\n * - Determinate indicators display how long a process will take.\n * - Indeterminate indicators express an unspecified amount of wait time.\n */\nlet MdCircularProgress = class MdCircularProgress extends CircularProgress {\n};\nMdCircularProgress.styles = [styles];\nMdCircularProgress = __decorate([\n    customElement('md-circular-progress')\n], MdCircularProgress);\nexport { MdCircularProgress };\n//# sourceMappingURL=circular-progress.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `@media(forced-colors: active){:host{--md-radio-disabled-selected-icon-color: GrayText;--md-radio-disabled-selected-icon-opacity: 1;--md-radio-disabled-unselected-icon-color: GrayText;--md-radio-disabled-unselected-icon-opacity: 1;--md-radio-selected-icon-color: CanvasText;--md-radio-selected-hover-icon-color: CanvasText;--md-radio-selected-focus-icon-color: CanvasText;--md-radio-selected-pressed-icon-color: CanvasText;--md-radio-unselected-icon-color: CanvasText;--md-radio-unselected-hover-icon-color: CanvasText;--md-radio-unselected-focus-icon-color: CanvasText;--md-radio-unselected-pressed-icon-color: CanvasText}}/*# sourceMappingURL=forced-colors-styles.css.map */\n`;\n//# sourceMappingURL=forced-colors-styles.css.js.map","/**\n * @license\n * Copyright 2022 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * A `ReactiveController` that provides root node-scoped single selection for\n * elements, similar to native `<input type=\"radio\">` selection.\n *\n * To use, elements should add the controller and call\n * `selectionController.handleCheckedChange()` in a getter/setter. This must\n * be synchronous to match native behavior.\n *\n * @example\n * const CHECKED = Symbol('checked');\n *\n * class MyToggle extends LitElement {\n *   get checked() { return this[CHECKED]; }\n *   set checked(checked: boolean) {\n *     const oldValue = this.checked;\n *     if (oldValue === checked) {\n *       return;\n *     }\n *\n *     this[CHECKED] = checked;\n *     this.selectionController.handleCheckedChange();\n *     this.requestUpdate('checked', oldValue);\n *   }\n *\n *   [CHECKED] = false;\n *\n *   private selectionController = new SingleSelectionController(this);\n *\n *   constructor() {\n *     super();\n *     this.addController(this.selectionController);\n *   }\n * }\n */\nexport class SingleSelectionController {\n    constructor(host) {\n        this.host = host;\n        this.focused = false;\n        this.root = null;\n        this.handleFocusIn = () => {\n            this.focused = true;\n            this.updateTabIndices();\n        };\n        this.handleFocusOut = () => {\n            this.focused = false;\n            this.updateTabIndices();\n        };\n        /**\n         * Handles arrow key events from the host. Using the arrow keys will\n         * select and check the next or previous sibling with the host's\n         * `name` attribute.\n         */\n        this.handleKeyDown = (event) => {\n            const isDown = event.key === 'ArrowDown';\n            const isUp = event.key === 'ArrowUp';\n            const isLeft = event.key === 'ArrowLeft';\n            const isRight = event.key === 'ArrowRight';\n            // Ignore non-arrow keys\n            if (!isLeft && !isRight && !isDown && !isUp) {\n                return;\n            }\n            // Don't try to select another sibling if there aren't any.\n            const siblings = this.getNamedSiblings();\n            if (!siblings.length) {\n                return;\n            }\n            // Prevent default interactions on the element for arrow keys,\n            // since this controller will introduce new behavior.\n            event.preventDefault();\n            // Check if moving forwards or backwards\n            const isRtl = getComputedStyle(this.host).direction === 'rtl';\n            const forwards = isRtl ? isLeft || isDown : isRight || isDown;\n            const hostIndex = siblings.indexOf(this.host);\n            let nextIndex = forwards ? hostIndex + 1 : hostIndex - 1;\n            // Search for the next sibling that is not disabled to select.\n            // If we return to the host index, there is nothing to select.\n            while (nextIndex !== hostIndex) {\n                if (nextIndex >= siblings.length) {\n                    // Return to start if moving past the last item.\n                    nextIndex = 0;\n                }\n                else if (nextIndex < 0) {\n                    // Go to end if moving before the first item.\n                    nextIndex = siblings.length - 1;\n                }\n                // Check if the next sibling is disabled. If so,\n                // move the index and continue searching.\n                const nextSibling = siblings[nextIndex];\n                if (nextSibling.hasAttribute('disabled')) {\n                    if (forwards) {\n                        nextIndex++;\n                    }\n                    else {\n                        nextIndex--;\n                    }\n                    continue;\n                }\n                // Uncheck and remove focusability from other siblings.\n                for (const sibling of siblings) {\n                    if (sibling !== nextSibling) {\n                        sibling.checked = false;\n                        sibling.tabIndex = -1;\n                    }\n                }\n                // The next sibling should be checked, focused and dispatch a change event\n                nextSibling.checked = true;\n                nextSibling.removeAttribute('tabindex');\n                nextSibling.focus();\n                // Fire a change event since the change is triggered by a user action.\n                // This matches native <input type=\"radio\"> behavior.\n                nextSibling.dispatchEvent(new Event('change', { bubbles: true }));\n                break;\n            }\n        };\n    }\n    hostConnected() {\n        this.root = this.host.getRootNode();\n        this.host.addEventListener('keydown', this.handleKeyDown);\n        this.host.addEventListener('focusin', this.handleFocusIn);\n        this.host.addEventListener('focusout', this.handleFocusOut);\n        if (this.host.checked) {\n            // Uncheck other siblings when attached if already checked. This mimics\n            // native <input type=\"radio\"> behavior.\n            this.uncheckSiblings();\n        }\n        // Update for the newly added host.\n        this.updateTabIndices();\n    }\n    hostDisconnected() {\n        this.host.removeEventListener('keydown', this.handleKeyDown);\n        this.host.removeEventListener('focusin', this.handleFocusIn);\n        this.host.removeEventListener('focusout', this.handleFocusOut);\n        // Update for siblings that are still connected.\n        this.updateTabIndices();\n        this.root = null;\n    }\n    /**\n     * Should be called whenever the host's `checked` property changes\n     * synchronously.\n     */\n    handleCheckedChange() {\n        if (!this.host.checked) {\n            return;\n        }\n        this.uncheckSiblings();\n        this.updateTabIndices();\n    }\n    uncheckSiblings() {\n        for (const sibling of this.getNamedSiblings()) {\n            if (sibling !== this.host) {\n                sibling.checked = false;\n            }\n        }\n    }\n    /**\n     * Updates the `tabindex` of the host and its siblings.\n     */\n    updateTabIndices() {\n        // There are three tabindex states for a group of elements:\n        // 1. If any are checked, that element is focusable.\n        const siblings = this.getNamedSiblings();\n        const checkedSibling = siblings.find(sibling => sibling.checked);\n        // 2. If an element is focused, the others are no longer focusable.\n        if (checkedSibling || this.focused) {\n            const focusable = checkedSibling || this.host;\n            focusable.removeAttribute('tabindex');\n            for (const sibling of siblings) {\n                if (sibling !== focusable) {\n                    sibling.tabIndex = -1;\n                }\n            }\n            return;\n        }\n        // 3. If none are checked or focused, all are focusable.\n        for (const sibling of siblings) {\n            sibling.removeAttribute('tabindex');\n        }\n    }\n    /**\n     * Retrieves all siblings in the host element's root with the same `name`\n     * attribute.\n     */\n    getNamedSiblings() {\n        const name = this.host.getAttribute('name');\n        if (!name || !this.root) {\n            return [];\n        }\n        return Array.from(this.root.querySelectorAll(`[name=\"${name}\"]`));\n    }\n}\n//# sourceMappingURL=single-selection-controller.js.map","/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nvar _a, _b;\nimport { __decorate } from \"tslib\";\nimport '../../focus/md-focus-ring.js';\nimport '../../ripple/ripple.js';\nimport { html, isServer, LitElement, nothing } from 'lit';\nimport { property, query } from 'lit/decorators.js';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { requestUpdateOnAriaChange } from '../../internal/aria/delegate.js';\nimport { dispatchActivationClick, isActivationClick, redispatchEvent } from '../../internal/controller/events.js';\nimport { SingleSelectionController } from './single-selection-controller.js';\nconst CHECKED = Symbol('checked');\nlet maskId = 0;\n/**\n * A radio component.\n */\nexport class Radio extends LitElement {\n    /**\n     * Whether or not the radio is selected.\n     */\n    get checked() {\n        return this[CHECKED];\n    }\n    set checked(checked) {\n        const wasChecked = this.checked;\n        if (wasChecked === checked) {\n            return;\n        }\n        this[CHECKED] = checked;\n        const state = String(checked);\n        this.internals.setFormValue(this.checked ? this.value : null, state);\n        this.requestUpdate('checked', wasChecked);\n        this.selectionController.handleCheckedChange();\n    }\n    /**\n     * The HTML name to use in form submission.\n     */\n    get name() {\n        return this.getAttribute('name') ?? '';\n    }\n    set name(name) {\n        this.setAttribute('name', name);\n    }\n    /**\n     * The associated form element with which this element's value will submit.\n     */\n    get form() {\n        return this.internals.form;\n    }\n    /**\n     * The labels this element is associated with.\n     */\n    get labels() {\n        return this.internals.labels;\n    }\n    constructor() {\n        super();\n        // Unique maskId is required because of a Safari bug that fail to persist\n        // reference to the mask. This should be removed once the bug is fixed.\n        this.maskId = `cutout${++maskId}`;\n        this[_b] = false;\n        /**\n         * Whether or not the radio is disabled.\n         */\n        this.disabled = false;\n        /**\n         * The element value to use in form submission when checked.\n         */\n        this.value = 'on';\n        this.selectionController = new SingleSelectionController(this);\n        this.internals = this /* needed for closure */.attachInternals();\n        this.addController(this.selectionController);\n        if (!isServer) {\n            this.addEventListener('click', (event) => {\n                if (!isActivationClick(event)) {\n                    return;\n                }\n                this.focus();\n                dispatchActivationClick(this.input);\n            });\n        }\n    }\n    focus() {\n        this.input?.focus();\n    }\n    render() {\n        const classes = { checked: this.checked };\n        // Needed for closure conformance\n        const { ariaLabel } = this;\n        return html `\n      <div class=${classMap(classes)}>\n        <md-ripple for=\"input\" ?disabled=${this.disabled}></md-ripple>\n        <md-focus-ring part=\"focus-ring\" for=\"input\"></md-focus-ring>\n        <svg class=\"icon\" viewBox=\"0 0 20 20\">\n          <mask id=\"${this.maskId}\">\n            <rect width=\"100%\" height=\"100%\" fill=\"white\" />\n            <circle cx=\"10\" cy=\"10\" r=\"8\" fill=\"black\" />\n          </mask>\n          <circle class=\"outer circle\" cx=\"10\" cy=\"10\" r=\"10\" mask=\"url(#${this.maskId})\" />\n          <circle class=\"inner circle\" cx=\"10\" cy=\"10\" r=\"5\" />\n        </svg>\n        <input\n          id=\"input\"\n          type=\"radio\"\n          name=${this.name}\n          aria-label=${ariaLabel || nothing}\n          .checked=${this.checked}\n          .value=${this.value}\n          ?disabled=${this.disabled}\n          @change=${this.handleChange}\n        >\n      </div>\n    `;\n    }\n    handleChange(event) {\n        if (this.disabled) {\n            return;\n        }\n        // Per spec, the change event on a radio input always represents checked.\n        this.checked = true;\n        redispatchEvent(this, event);\n    }\n    /** @private */\n    formResetCallback() {\n        // The checked property does not reflect, so the original attribute set by\n        // the user is used to determine the default value.\n        this.checked = this.hasAttribute('checked');\n    }\n    /** @private */\n    formStateRestoreCallback(state) {\n        this.checked = state === 'true';\n    }\n}\n_a = Radio, _b = CHECKED;\n(() => {\n    requestUpdateOnAriaChange(_a);\n})();\n/** @nocollapse */\nRadio.shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };\n/** @nocollapse */\nRadio.formAssociated = true;\n__decorate([\n    property({ type: Boolean })\n], Radio.prototype, \"checked\", null);\n__decorate([\n    property({ type: Boolean, reflect: true })\n], Radio.prototype, \"disabled\", void 0);\n__decorate([\n    property()\n], Radio.prototype, \"value\", void 0);\n__decorate([\n    query('input')\n], Radio.prototype, \"input\", void 0);\n//# sourceMappingURL=radio.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_disabled-selected-icon-color: var(--md-radio-disabled-selected-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-selected-icon-opacity: var(--md-radio-disabled-selected-icon-opacity, 0.38);--_disabled-unselected-icon-color: var(--md-radio-disabled-unselected-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-unselected-icon-opacity: var(--md-radio-disabled-unselected-icon-opacity, 0.38);--_icon-size: var(--md-radio-icon-size, 20px);--_selected-focus-icon-color: var(--md-radio-selected-focus-icon-color, var(--md-sys-color-primary, #6750a4));--_selected-hover-icon-color: var(--md-radio-selected-hover-icon-color, var(--md-sys-color-primary, #6750a4));--_selected-hover-state-layer-color: var(--md-radio-selected-hover-state-layer-color, var(--md-sys-color-primary, #6750a4));--_selected-hover-state-layer-opacity: var(--md-radio-selected-hover-state-layer-opacity, 0.08);--_selected-icon-color: var(--md-radio-selected-icon-color, var(--md-sys-color-primary, #6750a4));--_selected-pressed-icon-color: var(--md-radio-selected-pressed-icon-color, var(--md-sys-color-primary, #6750a4));--_selected-pressed-state-layer-color: var(--md-radio-selected-pressed-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--_selected-pressed-state-layer-opacity: var(--md-radio-selected-pressed-state-layer-opacity, 0.12);--_state-layer-size: var(--md-radio-state-layer-size, 40px);--_unselected-focus-icon-color: var(--md-radio-unselected-focus-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_unselected-hover-icon-color: var(--md-radio-unselected-hover-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_unselected-hover-state-layer-color: var(--md-radio-unselected-hover-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--_unselected-hover-state-layer-opacity: var(--md-radio-unselected-hover-state-layer-opacity, 0.08);--_unselected-icon-color: var(--md-radio-unselected-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_unselected-pressed-icon-color: var(--md-radio-unselected-pressed-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_unselected-pressed-state-layer-color: var(--md-radio-unselected-pressed-state-layer-color, var(--md-sys-color-primary, #6750a4));--_unselected-pressed-state-layer-opacity: var(--md-radio-unselected-pressed-state-layer-opacity, 0.12);--md-ripple-hover-color: var(--_unselected-hover-state-layer-color);--md-ripple-hover-opacity: var(--_unselected-hover-state-layer-opacity);--md-ripple-pressed-color: var(--_unselected-pressed-state-layer-color);--md-ripple-pressed-opacity: var(--_unselected-pressed-state-layer-opacity);display:inline-flex;height:48px;position:relative;vertical-align:top;width:48px;-webkit-tap-highlight-color:rgba(0,0,0,0)}md-focus-ring{--md-focus-ring-outward-offset: -2px}.checked{--md-ripple-hover-color: var(--_selected-hover-state-layer-color);--md-ripple-hover-opacity: var(--_selected-hover-state-layer-opacity);--md-ripple-pressed-color: var(--_selected-pressed-state-layer-color);--md-ripple-pressed-opacity: var(--_selected-pressed-state-layer-opacity)}input,.icon{inset:0;margin:auto;position:absolute}input{appearance:none;outline:none}md-ripple{border-radius:50%;height:var(--_state-layer-size);width:var(--_state-layer-size)}.icon{fill:var(--_unselected-icon-color);height:var(--_icon-size);width:var(--_icon-size)}.outer.circle{transition:fill 50ms linear}.inner.circle{opacity:0;transform-origin:center;transition:opacity 50ms linear}.checked .icon{fill:var(--_selected-icon-color)}.checked .inner.circle{animation:inner-circle-grow 300ms cubic-bezier(0.05, 0.7, 0.1, 1);opacity:1}@keyframes inner-circle-grow{from{transform:scale(0)}to{transform:scale(1)}}:host([disabled]) .circle{animation-duration:0s;transition-duration:0s}:host(:hover) .icon{fill:var(--_unselected-hover-icon-color)}:host(:focus-within) .icon{fill:var(--_unselected-focus-icon-color)}:host(:active) .icon{fill:var(--_unselected-pressed-icon-color)}:host([disabled]) .icon{fill:var(--_disabled-unselected-icon-color);opacity:var(--_disabled-unselected-icon-opacity)}:host(:hover) .checked .icon{fill:var(--_selected-hover-icon-color)}:host(:focus-within) .checked .icon{fill:var(--_selected-focus-icon-color)}:host(:active) .checked .icon{fill:var(--_selected-pressed-icon-color)}:host([disabled]) .checked .icon{fill:var(--_disabled-selected-icon-color);opacity:var(--_disabled-selected-icon-opacity)}/*# sourceMappingURL=radio-styles.css.map */\n`;\n//# sourceMappingURL=radio-styles.css.js.map","/**\n * @license\n * Copyright 2022 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { styles as forcedColorsStyles } from './internal/forced-colors-styles.css.js';\nimport { Radio } from './internal/radio.js';\nimport { styles } from './internal/radio-styles.css.js';\n/**\n * @summary Radio buttons allow users to select one option from a set.\n *\n * @description\n * Radio buttons are the recommended way to allow users to make a single\n * selection from a list of options.\n *\n * Only one radio button can be selected at a time.\n *\n * Use radio buttons to:\n * - Select a single option from a set\n * - Expose all available options\n *\n * @final\n * @suppress {visibility}\n */\nlet MdRadio = class MdRadio extends Radio {\n};\nMdRadio.styles = [styles, forcedColorsStyles];\nMdRadio = __decorate([\n    customElement('md-radio')\n], MdRadio);\nexport { MdRadio };\n//# sourceMappingURL=radio.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { html, LitElement, nothing, render } from 'lit';\nimport { property, query, queryAssignedElements, state } from 'lit/decorators.js';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { EASING } from '../../internal/motion/animation.js';\n/**\n * A field component.\n */\nexport class Field extends LitElement {\n    constructor() {\n        super(...arguments);\n        this.disabled = false;\n        this.error = false;\n        this.focused = false;\n        this.label = '';\n        this.populated = false;\n        this.required = false;\n        this.supportingText = '';\n        this.errorText = '';\n        this.count = -1;\n        this.max = -1;\n        /**\n         * Whether or not the field has leading content.\n         */\n        this.hasStart = false;\n        /**\n         * Whether or not the field has trailing content.\n         */\n        this.hasEnd = false;\n        this.isAnimating = false;\n        /**\n         * When set to true, the error text's `role=\"alert\"` will be removed, then\n         * re-added after an animation frame. This will re-announce an error message\n         * to screen readers.\n         */\n        this.refreshErrorAlert = false;\n    }\n    get counterText() {\n        if (this.count < 0 || this.max < 0) {\n            return '';\n        }\n        return `${this.count} / ${this.max}`;\n    }\n    get supportingOrErrorText() {\n        return this.error && this.errorText ? this.errorText : this.supportingText;\n    }\n    /**\n     * Re-announces the field's error supporting text to screen readers.\n     *\n     * Error text announces to screen readers anytime it is visible and changes.\n     * Use the method to re-announce the message when the text has not changed,\n     * but announcement is still needed (such as for `reportValidity()`).\n     */\n    reannounceError() {\n        this.refreshErrorAlert = true;\n    }\n    update(props) {\n        // Client-side property updates\n        // When disabling, remove focus styles if focused.\n        if (this.disabled && this.focused) {\n            props.set('focused', true);\n            this.focused = false;\n        }\n        // Animate if focused or populated change.\n        this.animateLabelIfNeeded({\n            wasFocused: props.get('focused'),\n            wasPopulated: props.get('populated')\n        });\n        super.update(props);\n    }\n    render() {\n        const floatingLabel = this.renderLabel(/*isFloating*/ true);\n        const restingLabel = this.renderLabel(/*isFloating*/ false);\n        const outline = this.renderOutline?.(floatingLabel);\n        const classes = {\n            'disabled': this.disabled,\n            'error': this.error && !this.disabled,\n            'focused': this.focused,\n            'with-start': this.hasStart,\n            'with-end': this.hasEnd,\n            'populated': this.populated,\n            'required': this.required,\n            'no-label': !this.label,\n        };\n        return html `\n      <div class=\"field ${classMap(classes)}\">\n        <div class=\"container-overflow\">\n          ${this.renderBackground?.()}\n          <div class=\"container\">\n            <div class=\"start\">\n              <slot name=\"start\"></slot>\n            </div>\n            <div class=\"middle\">\n              <div class=\"label-wrapper\">\n                ${restingLabel}\n                ${outline ? nothing : floatingLabel}\n              </div>\n              <div class=\"content\">\n                <slot></slot>\n              </div>\n            </div>\n            <div class=\"end\">\n              <slot name=\"end\"></slot>\n            </div>\n          </div>\n          ${outline}\n          ${this.renderIndicator?.()}\n        </div>\n        ${this.renderSupportingText()}\n      </div>\n    `;\n    }\n    updated(changed) {\n        if (changed.has('supportingText') || changed.has('errorText') ||\n            changed.has('count') || changed.has('max')) {\n            this.updateSlottedAriaDescribedBy();\n        }\n        if (this.refreshErrorAlert) {\n            // The past render cycle removed the role=\"alert\" from the error message.\n            // Re-add it after an animation frame to re-announce the error.\n            requestAnimationFrame(() => {\n                this.refreshErrorAlert = false;\n            });\n        }\n    }\n    renderSupportingText() {\n        const { supportingOrErrorText, counterText } = this;\n        if (!supportingOrErrorText && !counterText) {\n            return nothing;\n        }\n        // Always render the supporting text span so that our `space-around`\n        // container puts the counter at the end.\n        const start = html `<span>${supportingOrErrorText}</span>`;\n        // Conditionally render counter so we don't render the extra `gap`.\n        // TODO(b/244473435): add aria-label and announcements\n        const end = counterText ?\n            html `<span class=\"counter\">${counterText}</span>` :\n            nothing;\n        // Announce if there is an error and error text visible.\n        // If refreshErrorAlert is true, do not announce. This will remove the\n        // role=\"alert\" attribute. Another render cycle will happen after an\n        // animation frame to re-add the role.\n        const shouldErrorAnnounce = this.error && this.errorText && !this.refreshErrorAlert;\n        const role = shouldErrorAnnounce ? 'alert' : nothing;\n        return html `\n      <div class=\"supporting-text\" role=${role}>${start}${end}</div>\n      <slot name=\"aria-describedby\" @slotchange=${this.updateSlottedAriaDescribedBy}></slot>\n    `;\n    }\n    updateSlottedAriaDescribedBy() {\n        for (const element of this.slottedAriaDescribedBy) {\n            render(html `${this.supportingOrErrorText} ${this.counterText}`, element);\n            element.setAttribute('hidden', '');\n        }\n    }\n    renderLabel(isFloating) {\n        if (!this.label) {\n            return nothing;\n        }\n        let visible;\n        if (isFloating) {\n            // Floating label is visible when focused/populated or when animating.\n            visible = this.focused || this.populated || this.isAnimating;\n        }\n        else {\n            // Resting label is visible when unfocused. It is never visible while\n            // animating.\n            visible = !this.focused && !this.populated && !this.isAnimating;\n        }\n        const classes = {\n            'hidden': !visible,\n            'floating': isFloating,\n            'resting': !isFloating,\n        };\n        // Add '*' if a label is present and the field is required\n        const labelText = `${this.label}${this.required ? '*' : ''}`;\n        return html `\n      <span class=\"label ${classMap(classes)}\"\n        aria-hidden=${!visible}\n      >${labelText}</span>\n    `;\n    }\n    animateLabelIfNeeded({ wasFocused, wasPopulated }) {\n        if (!this.label) {\n            return;\n        }\n        wasFocused ?? (wasFocused = this.focused);\n        wasPopulated ?? (wasPopulated = this.populated);\n        const wasFloating = wasFocused || wasPopulated;\n        const shouldBeFloating = this.focused || this.populated;\n        if (wasFloating === shouldBeFloating) {\n            return;\n        }\n        this.isAnimating = true;\n        this.labelAnimation?.cancel();\n        // Only one label is visible at a time for clearer text rendering.\n        // The floating label is visible and used during animation. At the end of\n        // the animation, it will either remain visible (if floating) or hide and\n        // the resting label will be shown.\n        //\n        // We don't use forward filling because if the dimensions of the text field\n        // change (leading icon removed, density changes, etc), then the animation\n        // will be inaccurate.\n        //\n        // Re-calculating the animation each time will prevent any visual glitches\n        // from appearing.\n        // TODO(b/241113345): use animation tokens\n        this.labelAnimation = this.floatingLabelEl?.animate(this.getLabelKeyframes(), { duration: 150, easing: EASING.STANDARD });\n        this.labelAnimation?.addEventListener('finish', () => {\n            // At the end of the animation, update the visible label.\n            this.isAnimating = false;\n        });\n    }\n    getLabelKeyframes() {\n        const { floatingLabelEl, restingLabelEl } = this;\n        if (!floatingLabelEl || !restingLabelEl) {\n            return [];\n        }\n        const { x: floatingX, y: floatingY, height: floatingHeight } = floatingLabelEl.getBoundingClientRect();\n        const { x: restingX, y: restingY, height: restingHeight } = restingLabelEl.getBoundingClientRect();\n        const floatingScrollWidth = floatingLabelEl.scrollWidth;\n        const restingScrollWidth = restingLabelEl.scrollWidth;\n        // Scale by width ratio instead of font size since letter-spacing will scale\n        // incorrectly. Using the width we can better approximate the adjusted\n        // scale and compensate for tracking and overflow.\n        // (use scrollWidth instead of width to account for clipped labels)\n        const scale = restingScrollWidth / floatingScrollWidth;\n        const xDelta = restingX - floatingX;\n        // The line-height of the resting and floating label are different. When\n        // we move the floating label down to the resting label's position, it won't\n        // exactly match because of this. We need to adjust by half of what the\n        // final scaled floating label's height will be.\n        const yDelta = restingY - floatingY +\n            Math.round((restingHeight - floatingHeight * scale) / 2);\n        // Create the two transforms: floating to resting (using the calculations\n        // above), and resting to floating (re-setting the transform to initial\n        // values).\n        const restTransform = `translateX(${xDelta}px) translateY(${yDelta}px) scale(${scale})`;\n        const floatTransform = `translateX(0) translateY(0) scale(1)`;\n        // Constrain the floating labels width to a scaled percentage of the\n        // resting label's width. This will prevent long clipped labels from\n        // overflowing the container.\n        const restingClientWidth = restingLabelEl.clientWidth;\n        const isRestingClipped = restingScrollWidth > restingClientWidth;\n        const width = isRestingClipped ? `${restingClientWidth / scale}px` : '';\n        if (this.focused || this.populated) {\n            return [\n                { transform: restTransform, width }, { transform: floatTransform, width }\n            ];\n        }\n        return [\n            { transform: floatTransform, width }, { transform: restTransform, width }\n        ];\n    }\n    getSurfacePositionClientRect() {\n        return this.containerEl.getBoundingClientRect();\n    }\n}\n__decorate([\n    property({ type: Boolean })\n], Field.prototype, \"disabled\", void 0);\n__decorate([\n    property({ type: Boolean })\n], Field.prototype, \"error\", void 0);\n__decorate([\n    property({ type: Boolean })\n], Field.prototype, \"focused\", void 0);\n__decorate([\n    property()\n], Field.prototype, \"label\", void 0);\n__decorate([\n    property({ type: Boolean })\n], Field.prototype, \"populated\", void 0);\n__decorate([\n    property({ type: Boolean })\n], Field.prototype, \"required\", void 0);\n__decorate([\n    property({ attribute: 'supporting-text' })\n], Field.prototype, \"supportingText\", void 0);\n__decorate([\n    property({ attribute: 'error-text' })\n], Field.prototype, \"errorText\", void 0);\n__decorate([\n    property({ type: Number })\n], Field.prototype, \"count\", void 0);\n__decorate([\n    property({ type: Number })\n], Field.prototype, \"max\", void 0);\n__decorate([\n    property({ type: Boolean, attribute: 'has-start' })\n], Field.prototype, \"hasStart\", void 0);\n__decorate([\n    property({ type: Boolean, attribute: 'has-end' })\n], Field.prototype, \"hasEnd\", void 0);\n__decorate([\n    queryAssignedElements({ slot: 'aria-describedby' })\n], Field.prototype, \"slottedAriaDescribedBy\", void 0);\n__decorate([\n    state()\n], Field.prototype, \"isAnimating\", void 0);\n__decorate([\n    state()\n], Field.prototype, \"refreshErrorAlert\", void 0);\n__decorate([\n    query('.label.floating')\n], Field.prototype, \"floatingLabelEl\", void 0);\n__decorate([\n    query('.label.resting')\n], Field.prototype, \"restingLabelEl\", void 0);\n__decorate([\n    query('.container')\n], Field.prototype, \"containerEl\", void 0);\n//# sourceMappingURL=field.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { html } from 'lit';\nimport { Field } from './field.js';\n/**\n * An outlined field component.\n */\nexport class OutlinedField extends Field {\n    renderOutline(floatingLabel) {\n        return html `\n      <div class=\"outline\">\n        <div class=\"outline-start\"></div>\n        <div class=\"outline-notch\">\n          <div class=\"outline-panel-inactive\"></div>\n          <div class=\"outline-panel-active\"></div>\n          <div class=\"outline-label\">${floatingLabel}</div>\n        </div>\n        <div class=\"outline-end\"></div>\n      </div>\n    `;\n    }\n}\n//# sourceMappingURL=outlined-field.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_bottom-space: var(--md-outlined-field-bottom-space, 16px);--_container-shape: var(--md-outlined-field-container-shape, 4px);--_content-color: var(--md-outlined-field-content-color, var(--md-sys-color-on-surface, #1d1b20));--_content-type: var(--md-outlined-field-content-type, 400 1rem / 1.5rem var(--md-ref-typeface-plain, Roboto));--_disabled-content-color: var(--md-outlined-field-disabled-content-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-content-opacity: var(--md-outlined-field-disabled-content-opacity, 0.38);--_disabled-label-text-color: var(--md-outlined-field-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-outlined-field-disabled-label-text-opacity, 0.38);--_disabled-leading-content-color: var(--md-outlined-field-disabled-leading-content-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-leading-content-opacity: var(--md-outlined-field-disabled-leading-content-opacity, 0.38);--_disabled-outline-color: var(--md-outlined-field-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-outline-opacity: var(--md-outlined-field-disabled-outline-opacity, 0.12);--_disabled-outline-width: var(--md-outlined-field-disabled-outline-width, 1px);--_disabled-supporting-text-color: var(--md-outlined-field-disabled-supporting-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-supporting-text-opacity: var(--md-outlined-field-disabled-supporting-text-opacity, 0.38);--_disabled-trailing-content-color: var(--md-outlined-field-disabled-trailing-content-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-trailing-content-opacity: var(--md-outlined-field-disabled-trailing-content-opacity, 0.38);--_error-content-color: var(--md-outlined-field-error-content-color, var(--md-sys-color-on-surface, #1d1b20));--_error-focus-content-color: var(--md-outlined-field-error-focus-content-color, var(--md-sys-color-on-surface, #1d1b20));--_error-focus-label-text-color: var(--md-outlined-field-error-focus-label-text-color, var(--md-sys-color-error, #b3261e));--_error-focus-leading-content-color: var(--md-outlined-field-error-focus-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-focus-outline-color: var(--md-outlined-field-error-focus-outline-color, var(--md-sys-color-error, #b3261e));--_error-focus-supporting-text-color: var(--md-outlined-field-error-focus-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-focus-trailing-content-color: var(--md-outlined-field-error-focus-trailing-content-color, var(--md-sys-color-error, #b3261e));--_error-hover-content-color: var(--md-outlined-field-error-hover-content-color, var(--md-sys-color-on-surface, #1d1b20));--_error-hover-label-text-color: var(--md-outlined-field-error-hover-label-text-color, var(--md-sys-color-on-error-container, #410e0b));--_error-hover-leading-content-color: var(--md-outlined-field-error-hover-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-hover-outline-color: var(--md-outlined-field-error-hover-outline-color, var(--md-sys-color-on-error-container, #410e0b));--_error-hover-supporting-text-color: var(--md-outlined-field-error-hover-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-hover-trailing-content-color: var(--md-outlined-field-error-hover-trailing-content-color, var(--md-sys-color-on-error-container, #410e0b));--_error-label-text-color: var(--md-outlined-field-error-label-text-color, var(--md-sys-color-error, #b3261e));--_error-leading-content-color: var(--md-outlined-field-error-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-outline-color: var(--md-outlined-field-error-outline-color, var(--md-sys-color-error, #b3261e));--_error-supporting-text-color: var(--md-outlined-field-error-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-trailing-content-color: var(--md-outlined-field-error-trailing-content-color, var(--md-sys-color-error, #b3261e));--_focus-content-color: var(--md-outlined-field-focus-content-color, var(--md-sys-color-on-surface, #1d1b20));--_focus-label-text-color: var(--md-outlined-field-focus-label-text-color, var(--md-sys-color-primary, #6750a4));--_focus-leading-content-color: var(--md-outlined-field-focus-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_focus-outline-color: var(--md-outlined-field-focus-outline-color, var(--md-sys-color-primary, #6750a4));--_focus-outline-width: var(--md-outlined-field-focus-outline-width, 2px);--_focus-supporting-text-color: var(--md-outlined-field-focus-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_focus-trailing-content-color: var(--md-outlined-field-focus-trailing-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-content-color: var(--md-outlined-field-hover-content-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-label-text-color: var(--md-outlined-field-hover-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-leading-content-color: var(--md-outlined-field-hover-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-outline-color: var(--md-outlined-field-hover-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-outline-width: var(--md-outlined-field-hover-outline-width, 1px);--_hover-supporting-text-color: var(--md-outlined-field-hover-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-trailing-content-color: var(--md-outlined-field-hover-trailing-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_label-text-color: var(--md-outlined-field-label-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_label-text-padding-bottom: var(--md-outlined-field-label-text-padding-bottom, 8px);--_label-text-populated-line-height: var(--md-outlined-field-label-text-populated-line-height, 1rem);--_label-text-populated-size: var(--md-outlined-field-label-text-populated-size, 0.75rem);--_label-text-type: var(--md-outlined-field-label-text-type, 400 1rem / 1.5rem var(--md-ref-typeface-plain, Roboto));--_leading-content-color: var(--md-outlined-field-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_leading-space: var(--md-outlined-field-leading-space, 16px);--_outline-color: var(--md-outlined-field-outline-color, var(--md-sys-color-outline, #79747e));--_outline-label-padding: var(--md-outlined-field-outline-label-padding, 4px);--_outline-width: var(--md-outlined-field-outline-width, 1px);--_supporting-text-color: var(--md-outlined-field-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_supporting-text-leading-space: var(--md-outlined-field-supporting-text-leading-space, 16px);--_supporting-text-top-space: var(--md-outlined-field-supporting-text-top-space, 4px);--_supporting-text-trailing-space: var(--md-outlined-field-supporting-text-trailing-space, 16px);--_supporting-text-type: var(--md-outlined-field-supporting-text-type, 400 0.75rem / 1rem var(--md-ref-typeface-plain, Roboto));--_top-space: var(--md-outlined-field-top-space, 16px);--_trailing-content-color: var(--md-outlined-field-trailing-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_trailing-space: var(--md-outlined-field-trailing-space, 16px);--_container-shape-start-start: var( --md-outlined-field-container-shape-start-start, var(--_container-shape) );--_container-shape-start-end: var( --md-outlined-field-container-shape-start-end, var(--_container-shape) );--_container-shape-end-end: var( --md-outlined-field-container-shape-end-end, var(--_container-shape) );--_container-shape-end-start: var( --md-outlined-field-container-shape-end-start, var(--_container-shape) )}.outline{border-color:var(--_outline-color);border-radius:inherit;color:var(--_outline-color);display:flex;pointer-events:none;height:100%;position:absolute;width:100%}.outline-start::before,.outline-start::after,.outline-panel-inactive::before,.outline-panel-inactive::after,.outline-panel-active::before,.outline-panel-active::after,.outline-end::before,.outline-end::after{border:inherit;content:\"\";inset:0;position:absolute}.outline-start,.outline-end{border:inherit;border-radius:inherit;box-sizing:border-box;position:relative}.outline-start::before,.outline-start::after,.outline-end::before,.outline-end::after{border-bottom-style:solid;border-top-style:solid}.outline-start::after,.outline-end::after{opacity:0;transition:opacity 150ms cubic-bezier(0.2, 0, 0, 1)}.focused .outline-start::after,.focused .outline-end::after{opacity:1}.outline-start::before,.outline-start::after{border-inline-start-style:solid;border-inline-end-style:none;border-start-start-radius:inherit;border-start-end-radius:0;border-end-start-radius:inherit;border-end-end-radius:0;margin-inline-end:var(--_outline-label-padding)}.outline-end{flex-grow:1;margin-inline-start:calc(-1*var(--_outline-label-padding))}.outline-end::before,.outline-end::after{border-inline-start-style:none;border-inline-end-style:solid;border-start-start-radius:0;border-start-end-radius:inherit;border-end-start-radius:0;border-end-end-radius:inherit}.outline-notch{align-items:flex-start;border:inherit;display:flex;margin-inline-start:calc(-1*var(--_outline-label-padding));margin-inline-end:var(--_outline-label-padding);max-width:calc(100% - var(--_leading-space) - var(--_trailing-space));padding:0 var(--_outline-label-padding);position:relative}.no-label .outline-notch{display:none}.outline-panel-inactive,.outline-panel-active{border:inherit;border-bottom-style:solid;inset:0;position:absolute}.outline-panel-inactive::before,.outline-panel-inactive::after,.outline-panel-active::before,.outline-panel-active::after{border-top-style:solid;border-bottom:none;bottom:auto;transform:scaleX(1);transition:transform 150ms cubic-bezier(0.2, 0, 0, 1)}.outline-panel-inactive::before,.outline-panel-active::before{right:50%;transform-origin:top left}.outline-panel-inactive::after,.outline-panel-active::after{left:50%;transform-origin:top right}.populated .outline-panel-inactive::before,.populated .outline-panel-inactive::after,.populated .outline-panel-active::before,.populated .outline-panel-active::after,.focused .outline-panel-inactive::before,.focused .outline-panel-inactive::after,.focused .outline-panel-active::before,.focused .outline-panel-active::after{transform:scaleX(0)}.outline-panel-active{opacity:0;transition:opacity 150ms cubic-bezier(0.2, 0, 0, 1)}.focused .outline-panel-active{opacity:1}.outline-label{display:flex;max-width:100%;transform:translateY(calc(-100% + var(--_label-text-padding-bottom)))}.outline-start,.field:not(.with-start) .content ::slotted(*){padding-inline-start:max(var(--_leading-space),max(var(--_container-shape-start-start),var(--_container-shape-end-start)) + var(--_outline-label-padding))}.field:not(.with-start) .label-wrapper{margin-inline-start:max(var(--_leading-space),max(var(--_container-shape-start-start),var(--_container-shape-end-start)) + var(--_outline-label-padding))}.field:not(.with-end) .content ::slotted(*){padding-inline-end:max(var(--_trailing-space),max(var(--_container-shape-start-end),var(--_container-shape-end-end)))}.field:not(.with-end) .label-wrapper{margin-inline-end:max(var(--_trailing-space),max(var(--_container-shape-start-end),var(--_container-shape-end-end)))}.outline-start::before,.outline-end::before,.outline-panel-inactive,.outline-panel-inactive::before,.outline-panel-inactive::after{border-width:var(--_outline-width)}:hover .outline{border-color:var(--_hover-outline-color);color:var(--_hover-outline-color)}:hover .outline-start::before,:hover .outline-end::before,:hover .outline-panel-inactive,:hover .outline-panel-inactive::before,:hover .outline-panel-inactive::after{border-width:var(--_hover-outline-width)}.focused .outline{border-color:var(--_focus-outline-color);color:var(--_focus-outline-color)}.outline-start::after,.outline-end::after,.outline-panel-active,.outline-panel-active::before,.outline-panel-active::after{border-width:var(--_focus-outline-width)}.disabled .outline{border-color:var(--_disabled-outline-color);color:var(--_disabled-outline-color)}.disabled .outline-start,.disabled .outline-end,.disabled .outline-panel-inactive{opacity:var(--_disabled-outline-opacity)}.disabled .outline-start::before,.disabled .outline-end::before,.disabled .outline-panel-inactive,.disabled .outline-panel-inactive::before,.disabled .outline-panel-inactive::after{border-width:var(--_disabled-outline-width)}.error .outline{border-color:var(--_error-outline-color);color:var(--_error-outline-color)}.error:hover .outline{border-color:var(--_error-hover-outline-color);color:var(--_error-hover-outline-color)}.error.focused .outline{border-color:var(--_error-focus-outline-color);color:var(--_error-focus-outline-color)}/*# sourceMappingURL=outlined-styles.css.map */\n`;\n//# sourceMappingURL=outlined-styles.css.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{display:inline-flex}.field{display:flex;flex:1;flex-direction:column;writing-mode:horizontal-tb;max-width:100%}.container-overflow{border-start-start-radius:var(--_container-shape-start-start);border-start-end-radius:var(--_container-shape-start-end);border-end-end-radius:var(--_container-shape-end-end);border-end-start-radius:var(--_container-shape-end-start);display:flex;height:100%;position:relative}.container{align-items:center;border-radius:inherit;display:flex;flex:1;max-height:100%;min-height:100%;min-width:min-content;overflow:hidden;position:relative}.field,.container-overflow,.field:not(.disabled) .container{resize:inherit}.disabled{pointer-events:none}.start,.middle,.end{display:flex;box-sizing:border-box;height:100%;position:relative}.start{color:var(--_leading-content-color)}.end{color:var(--_trailing-content-color)}.start,.end{align-items:center;justify-content:center}.with-start .start,.with-end .end{min-width:48px}.with-start .start{margin-inline-end:4px}.with-end .end{margin-inline-start:4px}.middle{align-items:stretch;align-self:baseline;flex:1}.content{color:var(--_content-color);display:flex;flex:1;opacity:0;transition:opacity 83ms cubic-bezier(0.2, 0, 0, 1)}.no-label .content,.focused .content,.populated .content{opacity:1;transition-delay:67ms}.content ::slotted(*){all:unset;color:currentColor;font:var(--_content-type);width:100%}.content ::slotted(:not(textarea)){padding-top:var(--_top-space);padding-bottom:var(--_bottom-space)}.content ::slotted(textarea){margin-top:var(--_top-space);margin-bottom:var(--_bottom-space)}:hover .content{color:var(--_hover-content-color)}:hover .start{color:var(--_hover-leading-content-color)}:hover .end{color:var(--_hover-trailing-content-color)}.focused .content{color:var(--_focus-content-color)}.focused .start{color:var(--_focus-leading-content-color)}.focused .end{color:var(--_focus-trailing-content-color)}.disabled .content{color:var(--_disabled-content-color)}.disabled.no-label .content,.disabled.focused .content,.disabled.populated .content{opacity:var(--_disabled-content-opacity)}.disabled .start{color:var(--_disabled-leading-content-color);opacity:var(--_disabled-leading-content-opacity)}.disabled .end{color:var(--_disabled-trailing-content-color);opacity:var(--_disabled-trailing-content-opacity)}.error .content{color:var(--_error-content-color)}.error .start{color:var(--_error-leading-content-color)}.error .end{color:var(--_error-trailing-content-color)}.error:hover .content{color:var(--_error-hover-content-color)}.error:hover .start{color:var(--_error-hover-leading-content-color)}.error:hover .end{color:var(--_error-hover-trailing-content-color)}.error.focused .content{color:var(--_error-focus-content-color)}.error.focused .start{color:var(--_error-focus-leading-content-color)}.error.focused .end{color:var(--_error-focus-trailing-content-color)}.label{box-sizing:border-box;color:var(--_label-text-color);overflow:hidden;max-width:100%;text-overflow:ellipsis;white-space:nowrap;z-index:1;font:var(--_label-text-type);width:min-content}.label-wrapper{inset:0;pointer-events:none;position:absolute}.label.resting{position:absolute;top:var(--_top-space)}.label.floating{font-size:var(--_label-text-populated-size);line-height:var(--_label-text-populated-line-height);transform-origin:top left}.label.hidden{opacity:0}.no-label .label{display:none}.label-wrapper{inset:0;position:absolute;text-align:initial}:hover .label{color:var(--_hover-label-text-color)}.focused .label{color:var(--_focus-label-text-color)}.disabled .label{color:var(--_disabled-label-text-color)}.disabled .label:not(.hidden){opacity:var(--_disabled-label-text-opacity)}.error .label{color:var(--_error-label-text-color)}.error:hover .label{color:var(--_error-hover-label-text-color)}.error.focused .label{color:var(--_error-focus-label-text-color)}.supporting-text{color:var(--_supporting-text-color);display:flex;font:var(--_supporting-text-type);gap:16px;justify-content:space-between;padding-inline-start:var(--_supporting-text-leading-space);padding-inline-end:var(--_supporting-text-trailing-space);padding-top:var(--_supporting-text-top-space)}.supporting-text :nth-child(2){flex-shrink:0}:hover .supporting-text{color:var(--_hover-supporting-text-color)}.focus .supporting-text{color:var(--_focus-supporting-text-color)}.disabled .supporting-text{color:var(--_disabled-supporting-text-color);opacity:var(--_disabled-supporting-text-opacity)}.error .supporting-text{color:var(--_error-supporting-text-color)}.error:hover .supporting-text{color:var(--_error-hover-supporting-text-color)}.error.focus .supporting-text{color:var(--_error-focus-supporting-text-color)}/*# sourceMappingURL=shared-styles.css.map */\n`;\n//# sourceMappingURL=shared-styles.css.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport { customElement } from 'lit/decorators.js';\nimport { OutlinedField } from './internal/outlined-field.js';\nimport { styles as outlinedStyles } from './internal/outlined-styles.css.js';\nimport { styles as sharedStyles } from './internal/shared-styles.css.js';\n/**\n * TODO(b/228525797): add docs\n * @final\n * @suppress {visibility}\n */\nlet MdOutlinedField = class MdOutlinedField extends OutlinedField {\n};\nMdOutlinedField.styles = [sharedStyles, outlinedStyles];\nMdOutlinedField = __decorate([\n    customElement('md-outlined-field')\n], MdOutlinedField);\nexport { MdOutlinedField };\n//# sourceMappingURL=outlined-field.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `@media(forced-colors: active){:host{--md-outlined-text-field-disabled-input-text-color: GrayText;--md-outlined-text-field-disabled-input-text-opacity: 1;--md-outlined-text-field-disabled-label-text-color: GrayText;--md-outlined-text-field-disabled-label-text-opacity: 1;--md-outlined-text-field-disabled-leading-icon-color: GrayText;--md-outlined-text-field-disabled-leading-icon-opacity: 1;--md-outlined-text-field-disabled-outline-color: GrayText;--md-outlined-text-field-disabled-outline-opacity: 1;--md-outlined-text-field-disabled-supporting-text-color: GrayText;--md-outlined-text-field-disabled-supporting-text-opacity: 1;--md-outlined-text-field-disabled-trailing-icon-color: GrayText;--md-outlined-text-field-disabled-trailing-icon-opacity: 1}}/*# sourceMappingURL=outlined-forced-colors-styles.css.map */\n`;\n//# sourceMappingURL=outlined-forced-colors-styles.css.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{--_leading-space: var(--md-outlined-text-field-leading-space, 16px);--_trailing-space: var(--md-outlined-text-field-trailing-space, 16px);--_top-space: var(--md-outlined-text-field-top-space, 16px);--_bottom-space: var(--md-outlined-text-field-bottom-space, 16px);--_input-text-prefix-trailing-space: var(--md-outlined-text-field-input-text-prefix-trailing-space, 2px);--_input-text-suffix-leading-space: var(--md-outlined-text-field-input-text-suffix-leading-space, 2px);--_focus-caret-color: var(--md-outlined-text-field-focus-caret-color, var(--md-sys-color-primary, #6750a4));--_caret-color: var(--md-outlined-text-field-caret-color, var(--md-sys-color-primary, #6750a4));--_container-shape: var(--md-outlined-text-field-container-shape, 4px);--_disabled-input-text-color: var(--md-outlined-text-field-disabled-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-input-text-opacity: var(--md-outlined-text-field-disabled-input-text-opacity, 0.38);--_disabled-label-text-color: var(--md-outlined-text-field-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-outlined-text-field-disabled-label-text-opacity, 0.38);--_disabled-leading-icon-color: var(--md-outlined-text-field-disabled-leading-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-leading-icon-opacity: var(--md-outlined-text-field-disabled-leading-icon-opacity, 0.38);--_disabled-outline-color: var(--md-outlined-text-field-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-outline-opacity: var(--md-outlined-text-field-disabled-outline-opacity, 0.12);--_disabled-outline-width: var(--md-outlined-text-field-disabled-outline-width, 1px);--_disabled-supporting-text-color: var(--md-outlined-text-field-disabled-supporting-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-supporting-text-opacity: var(--md-outlined-text-field-disabled-supporting-text-opacity, 0.38);--_disabled-trailing-icon-color: var(--md-outlined-text-field-disabled-trailing-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-trailing-icon-opacity: var(--md-outlined-text-field-disabled-trailing-icon-opacity, 0.38);--_error-focus-caret-color: var(--md-outlined-text-field-error-focus-caret-color, var(--md-sys-color-error, #b3261e));--_error-focus-input-text-color: var(--md-outlined-text-field-error-focus-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_error-focus-label-text-color: var(--md-outlined-text-field-error-focus-label-text-color, var(--md-sys-color-error, #b3261e));--_error-focus-leading-icon-color: var(--md-outlined-text-field-error-focus-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-focus-outline-color: var(--md-outlined-text-field-error-focus-outline-color, var(--md-sys-color-error, #b3261e));--_error-focus-supporting-text-color: var(--md-outlined-text-field-error-focus-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-focus-trailing-icon-color: var(--md-outlined-text-field-error-focus-trailing-icon-color, var(--md-sys-color-error, #b3261e));--_error-hover-input-text-color: var(--md-outlined-text-field-error-hover-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_error-hover-label-text-color: var(--md-outlined-text-field-error-hover-label-text-color, var(--md-sys-color-on-error-container, #410e0b));--_error-hover-leading-icon-color: var(--md-outlined-text-field-error-hover-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-hover-outline-color: var(--md-outlined-text-field-error-hover-outline-color, var(--md-sys-color-on-error-container, #410e0b));--_error-hover-supporting-text-color: var(--md-outlined-text-field-error-hover-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-hover-trailing-icon-color: var(--md-outlined-text-field-error-hover-trailing-icon-color, var(--md-sys-color-on-error-container, #410e0b));--_error-input-text-color: var(--md-outlined-text-field-error-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_error-label-text-color: var(--md-outlined-text-field-error-label-text-color, var(--md-sys-color-error, #b3261e));--_error-leading-icon-color: var(--md-outlined-text-field-error-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-outline-color: var(--md-outlined-text-field-error-outline-color, var(--md-sys-color-error, #b3261e));--_error-supporting-text-color: var(--md-outlined-text-field-error-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-trailing-icon-color: var(--md-outlined-text-field-error-trailing-icon-color, var(--md-sys-color-error, #b3261e));--_focus-input-text-color: var(--md-outlined-text-field-focus-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_focus-label-text-color: var(--md-outlined-text-field-focus-label-text-color, var(--md-sys-color-primary, #6750a4));--_focus-leading-icon-color: var(--md-outlined-text-field-focus-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_focus-outline-color: var(--md-outlined-text-field-focus-outline-color, var(--md-sys-color-primary, #6750a4));--_focus-outline-width: var(--md-outlined-text-field-focus-outline-width, 2px);--_focus-supporting-text-color: var(--md-outlined-text-field-focus-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_focus-trailing-icon-color: var(--md-outlined-text-field-focus-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-input-text-color: var(--md-outlined-text-field-hover-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-label-text-color: var(--md-outlined-text-field-hover-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-leading-icon-color: var(--md-outlined-text-field-hover-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-outline-color: var(--md-outlined-text-field-hover-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-outline-width: var(--md-outlined-text-field-hover-outline-width, 1px);--_hover-supporting-text-color: var(--md-outlined-text-field-hover-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-trailing-icon-color: var(--md-outlined-text-field-hover-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_input-text-color: var(--md-outlined-text-field-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_input-text-placeholder-color: var(--md-outlined-text-field-input-text-placeholder-color, var(--md-sys-color-on-surface-variant, #49454f));--_input-text-prefix-color: var(--md-outlined-text-field-input-text-prefix-color, var(--md-sys-color-on-surface-variant, #49454f));--_input-text-suffix-color: var(--md-outlined-text-field-input-text-suffix-color, var(--md-sys-color-on-surface-variant, #49454f));--_input-text-type: var(--md-outlined-text-field-input-text-type, var(--md-sys-typescale-body-large, 400 1rem / 1.5rem var(--md-ref-typeface-plain, Roboto)));--_label-text-color: var(--md-outlined-text-field-label-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_label-text-populated-line-height: var(--md-outlined-text-field-label-text-populated-line-height, 1rem);--_label-text-populated-size: var(--md-outlined-text-field-label-text-populated-size, 0.75rem);--_label-text-type: var(--md-outlined-text-field-label-text-type, var(--md-sys-typescale-body-large, 400 1rem / 1.5rem var(--md-ref-typeface-plain, Roboto)));--_leading-icon-color: var(--md-outlined-text-field-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_leading-icon-size: var(--md-outlined-text-field-leading-icon-size, 24px);--_outline-color: var(--md-outlined-text-field-outline-color, var(--md-sys-color-outline, #79747e));--_outline-width: var(--md-outlined-text-field-outline-width, 1px);--_supporting-text-color: var(--md-outlined-text-field-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_supporting-text-type: var(--md-outlined-text-field-supporting-text-type, var(--md-sys-typescale-body-small, 400 0.75rem / 1rem var(--md-ref-typeface-plain, Roboto)));--_trailing-icon-color: var(--md-outlined-text-field-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_trailing-icon-size: var(--md-outlined-text-field-trailing-icon-size, 24px);--_container-shape-start-start: var( --md-outlined-text-field-container-shape-start-start, var(--_container-shape) );--_container-shape-start-end: var( --md-outlined-text-field-container-shape-start-end, var(--_container-shape) );--_container-shape-end-end: var( --md-outlined-text-field-container-shape-end-end, var(--_container-shape) );--_container-shape-end-start: var( --md-outlined-text-field-container-shape-end-start, var(--_container-shape) );--md-outlined-field-bottom-space: var(--_bottom-space);--md-outlined-field-container-shape-end-end: var(--_container-shape-end-end);--md-outlined-field-container-shape-end-start: var(--_container-shape-end-start);--md-outlined-field-container-shape-start-end: var(--_container-shape-start-end);--md-outlined-field-container-shape-start-start: var(--_container-shape-start-start);--md-outlined-field-content-color: var(--_input-text-color);--md-outlined-field-content-type: var(--_input-text-type);--md-outlined-field-disabled-content-color: var(--_disabled-input-text-color);--md-outlined-field-disabled-content-opacity: var(--_disabled-input-text-opacity);--md-outlined-field-disabled-label-text-color: var(--_disabled-label-text-color);--md-outlined-field-disabled-label-text-opacity: var(--_disabled-label-text-opacity);--md-outlined-field-disabled-leading-content-color: var(--_disabled-leading-icon-color);--md-outlined-field-disabled-leading-content-opacity: var(--_disabled-leading-icon-opacity);--md-outlined-field-disabled-outline-color: var(--_disabled-outline-color);--md-outlined-field-disabled-outline-opacity: var(--_disabled-outline-opacity);--md-outlined-field-disabled-outline-width: var(--_disabled-outline-width);--md-outlined-field-disabled-supporting-text-color: var(--_disabled-supporting-text-color);--md-outlined-field-disabled-supporting-text-opacity: var(--_disabled-supporting-text-opacity);--md-outlined-field-disabled-trailing-content-color: var(--_disabled-trailing-icon-color);--md-outlined-field-disabled-trailing-content-opacity: var(--_disabled-trailing-icon-opacity);--md-outlined-field-error-content-color: var(--_error-input-text-color);--md-outlined-field-error-focus-content-color: var(--_error-focus-input-text-color);--md-outlined-field-error-focus-label-text-color: var(--_error-focus-label-text-color);--md-outlined-field-error-focus-leading-content-color: var(--_error-focus-leading-icon-color);--md-outlined-field-error-focus-outline-color: var(--_error-focus-outline-color);--md-outlined-field-error-focus-supporting-text-color: var(--_error-focus-supporting-text-color);--md-outlined-field-error-focus-trailing-content-color: var(--_error-focus-trailing-icon-color);--md-outlined-field-error-hover-content-color: var(--_error-hover-input-text-color);--md-outlined-field-error-hover-label-text-color: var(--_error-hover-label-text-color);--md-outlined-field-error-hover-leading-content-color: var(--_error-hover-leading-icon-color);--md-outlined-field-error-hover-outline-color: var(--_error-hover-outline-color);--md-outlined-field-error-hover-supporting-text-color: var(--_error-hover-supporting-text-color);--md-outlined-field-error-hover-trailing-content-color: var(--_error-hover-trailing-icon-color);--md-outlined-field-error-label-text-color: var(--_error-label-text-color);--md-outlined-field-error-leading-content-color: var(--_error-leading-icon-color);--md-outlined-field-error-outline-color: var(--_error-outline-color);--md-outlined-field-error-supporting-text-color: var(--_error-supporting-text-color);--md-outlined-field-error-trailing-content-color: var(--_error-trailing-icon-color);--md-outlined-field-focus-content-color: var(--_focus-input-text-color);--md-outlined-field-focus-label-text-color: var(--_focus-label-text-color);--md-outlined-field-focus-leading-content-color: var(--_focus-leading-icon-color);--md-outlined-field-focus-outline-color: var(--_focus-outline-color);--md-outlined-field-focus-outline-width: var(--_focus-outline-width);--md-outlined-field-focus-supporting-text-color: var(--_focus-supporting-text-color);--md-outlined-field-focus-trailing-content-color: var(--_focus-trailing-icon-color);--md-outlined-field-hover-content-color: var(--_hover-input-text-color);--md-outlined-field-hover-label-text-color: var(--_hover-label-text-color);--md-outlined-field-hover-leading-content-color: var(--_hover-leading-icon-color);--md-outlined-field-hover-outline-color: var(--_hover-outline-color);--md-outlined-field-hover-outline-width: var(--_hover-outline-width);--md-outlined-field-hover-supporting-text-color: var(--_hover-supporting-text-color);--md-outlined-field-hover-trailing-content-color: var(--_hover-trailing-icon-color);--md-outlined-field-label-text-color: var(--_label-text-color);--md-outlined-field-label-text-populated-line-height: var(--_label-text-populated-line-height);--md-outlined-field-label-text-populated-size: var(--_label-text-populated-size);--md-outlined-field-label-text-type: var(--_label-text-type);--md-outlined-field-leading-content-color: var(--_leading-icon-color);--md-outlined-field-leading-space: var(--_leading-space);--md-outlined-field-outline-color: var(--_outline-color);--md-outlined-field-outline-width: var(--_outline-width);--md-outlined-field-supporting-text-color: var(--_supporting-text-color);--md-outlined-field-supporting-text-type: var(--_supporting-text-type);--md-outlined-field-top-space: var(--_top-space);--md-outlined-field-trailing-content-color: var(--_trailing-icon-color);--md-outlined-field-trailing-space: var(--_trailing-space)}/*# sourceMappingURL=outlined-styles.css.map */\n`;\n//# sourceMappingURL=outlined-styles.css.js.map","import{_$LH as o}from\"./lit-html.js\";\n/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const{I:l}=o,t=o=>null===o||\"object\"!=typeof o&&\"function\"!=typeof o,i={HTML:1,SVG:2},n=(o,l)=>void 0===l?void 0!==(null==o?void 0:o._$litType$):(null==o?void 0:o._$litType$)===l,d=o=>void 0!==(null==o?void 0:o._$litDirective$),v=o=>null==o?void 0:o._$litDirective$,e=o=>void 0===o.strings,c=()=>document.createComment(\"\"),r=(o,t,i)=>{var n;const d=o._$AA.parentNode,v=void 0===t?o._$AB:t._$AA;if(void 0===i){const t=d.insertBefore(c(),v),n=d.insertBefore(c(),v);i=new l(t,n,o,o.options)}else{const l=i._$AB.nextSibling,t=i._$AM,e=t!==o;if(e){let l;null===(n=i._$AQ)||void 0===n||n.call(i,o),i._$AM=o,void 0!==i._$AP&&(l=o._$AU)!==t._$AU&&i._$AP(l)}if(l!==v||e){let o=i._$AA;for(;o!==l;){const l=o.nextSibling;d.insertBefore(o,v),o=l}}}return i},u=(o,l,t=o)=>(o._$AI(l,t),o),f={},s=(o,l=f)=>o._$AH=l,m=o=>o._$AH,p=o=>{var l;null===(l=o._$AP)||void 0===l||l.call(o,!1,!0);let t=o._$AA;const i=o._$AB.nextSibling;for(;t!==i;){const o=t.nextSibling;t.remove(),t=o}},a=o=>{o._$AR()};export{i as TemplateResultType,a as clearPart,m as getCommittedValue,v as getDirectiveClass,r as insertPart,d as isDirectiveResult,t as isPrimitive,e as isSingleExpression,n as isTemplateResult,p as removePart,u as setChildPartValue,s as setCommittedValue};\n//# sourceMappingURL=directive-helpers.js.map\n","import{noChange as r,nothing as e}from\"../lit-html.js\";import{directive as i,Directive as t,PartType as n}from\"../directive.js\";import{isSingleExpression as o,setCommittedValue as s}from\"../directive-helpers.js\";\n/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const l=i(class extends t{constructor(r){if(super(r),r.type!==n.PROPERTY&&r.type!==n.ATTRIBUTE&&r.type!==n.BOOLEAN_ATTRIBUTE)throw Error(\"The `live` directive is not allowed on child or event bindings\");if(!o(r))throw Error(\"`live` bindings can only contain a single expression\")}render(r){return r}update(i,[t]){if(t===r||t===e)return t;const o=i.element,l=i.name;if(i.type===n.PROPERTY){if(t===o[l])return r}else if(i.type===n.BOOLEAN_ATTRIBUTE){if(!!t===o.hasAttribute(l))return r}else if(i.type===n.ATTRIBUTE&&o.getAttribute(l)===t+\"\")return r;return s(i),t}});export{l as live};\n//# sourceMappingURL=live.js.map\n","import{noChange as t}from\"../lit-html.js\";import{directive as e,Directive as r,PartType as s}from\"../directive.js\";\n/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const i=\"important\",n=\" !\"+i,o=e(class extends r{constructor(t){var e;if(super(t),t.type!==s.ATTRIBUTE||\"style\"!==t.name||(null===(e=t.strings)||void 0===e?void 0:e.length)>2)throw Error(\"The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.\")}render(t){return Object.keys(t).reduce(((e,r)=>{const s=t[r];return null==s?e:e+`${r=r.includes(\"-\")?r:r.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,\"-$&\").toLowerCase()}:${s};`}),\"\")}update(e,[r]){const{style:s}=e.element;if(void 0===this.ut){this.ut=new Set;for(const t in r)this.ut.add(t);return this.render(r)}this.ut.forEach((t=>{null==r[t]&&(this.ut.delete(t),t.includes(\"-\")?s.removeProperty(t):s[t]=\"\")}));for(const t in r){const e=r[t];if(null!=e){this.ut.add(t);const r=\"string\"==typeof e&&e.endsWith(n);t.includes(\"-\")||r?s.setProperty(t,r?e.slice(0,-11):e,r?i:\"\"):s[t]=e}}return t}});export{o as styleMap};\n//# sourceMappingURL=style-map.js.map\n","/**\n * @license\n * Copyright 2022 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nexport const stringConverter = {\n    fromAttribute(value) {\n        return value ?? '';\n    },\n    toAttribute(value) {\n        return value || null;\n    }\n};\n//# sourceMappingURL=string-converter.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nvar _a;\nimport { __decorate } from \"tslib\";\nimport { html, isServer, LitElement, nothing } from 'lit';\nimport { property, query, queryAssignedElements, state } from 'lit/decorators.js';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { live } from 'lit/directives/live.js';\nimport { styleMap } from 'lit/directives/style-map.js';\nimport { html as staticHtml } from 'lit/static-html.js';\nimport { requestUpdateOnAriaChange } from '../../internal/aria/delegate.js';\nimport { redispatchEvent } from '../../internal/controller/events.js';\nimport { stringConverter } from '../../internal/controller/string-converter.js';\n/**\n * A text field component.\n */\nexport class TextField extends LitElement {\n    /**\n     * The associated form element with which this element's value will submit.\n     */\n    get form() {\n        return this.internals.form;\n    }\n    /**\n     * The labels this element is associated with.\n     */\n    get labels() {\n        return this.internals.labels;\n    }\n    /**\n     * The HTML name to use in form submission.\n     */\n    get name() {\n        return this.getAttribute('name') ?? '';\n    }\n    set name(name) {\n        this.setAttribute('name', name);\n    }\n    /**\n     * Gets or sets the direction in which selection occurred.\n     */\n    get selectionDirection() {\n        return this.getInputOrTextarea().selectionDirection;\n    }\n    set selectionDirection(value) {\n        this.getInputOrTextarea().selectionDirection = value;\n    }\n    /**\n     * Gets or sets the end position or offset of a text selection.\n     */\n    get selectionEnd() {\n        return this.getInputOrTextarea().selectionEnd;\n    }\n    set selectionEnd(value) {\n        this.getInputOrTextarea().selectionEnd = value;\n    }\n    /**\n     * Gets or sets the starting position or offset of a text selection.\n     */\n    get selectionStart() {\n        return this.getInputOrTextarea().selectionStart;\n    }\n    set selectionStart(value) {\n        this.getInputOrTextarea().selectionStart = value;\n    }\n    /**\n     * Returns the native validation error message that would be displayed upon\n     * calling `reportValidity()`.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/validationMessage\n     */\n    get validationMessage() {\n        return this.getInputOrTextarea().validationMessage;\n    }\n    /**\n     * Returns a ValidityState object that represents the validity states of the\n     * text field.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/validity\n     */\n    get validity() {\n        return this.getInputOrTextarea().validity;\n    }\n    /**\n     * The text field's value as a number.\n     */\n    get valueAsNumber() {\n        const input = this.getInput();\n        if (!input) {\n            return NaN;\n        }\n        return input.valueAsNumber;\n    }\n    set valueAsNumber(value) {\n        const input = this.getInput();\n        if (!input) {\n            return;\n        }\n        input.valueAsNumber = value;\n        this.value = input.value;\n    }\n    /**\n     * The text field's value as a Date.\n     */\n    get valueAsDate() {\n        const input = this.getInput();\n        if (!input) {\n            return null;\n        }\n        return input.valueAsDate;\n    }\n    set valueAsDate(value) {\n        const input = this.getInput();\n        if (!input) {\n            return;\n        }\n        input.valueAsDate = value;\n        this.value = input.value;\n    }\n    /**\n     * Returns whether an element will successfully validate based on forms\n     * validation rules and constraints.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/willValidate\n     */\n    get willValidate() {\n        return this.getInputOrTextarea().willValidate;\n    }\n    get hasError() {\n        return this.error || this.nativeError;\n    }\n    constructor() {\n        super();\n        this.disabled = false;\n        /**\n         * Gets or sets whether or not the text field is in a visually invalid state.\n         *\n         * Calling `reportValidity()` will automatically update `error`.\n         */\n        this.error = false;\n        /**\n         * The error message that replaces supporting text when `error` is true. If\n         * `errorText` is an empty string, then the supporting text will continue to\n         * show.\n         *\n         * Calling `reportValidity()` will automatically update `errorText` to the\n         * native `validationMessage`.\n         */\n        this.errorText = '';\n        this.label = '';\n        this.required = false;\n        /**\n         * The current value of the text field. It is always a string.\n         */\n        this.value = '';\n        /**\n         * An optional prefix to display before the input value.\n         */\n        this.prefixText = '';\n        /**\n         * An optional suffix to display after the input value.\n         */\n        this.suffixText = '';\n        /**\n         * Whether or not the text field has a leading icon. Used for SSR.\n         */\n        this.hasLeadingIcon = false;\n        /**\n         * Whether or not the text field has a trailing icon. Used for SSR.\n         */\n        this.hasTrailingIcon = false;\n        /**\n         * Conveys additional information below the text field, such as how it should\n         * be used.\n         */\n        this.supportingText = '';\n        /**\n         * Override the input text CSS `direction`. Useful for RTL languages that use\n         * LTR notation for fractions.\n         */\n        this.textDirection = '';\n        /**\n         * The number of rows to display for a `type=\"textarea\"` text field.\n         * Defaults to 2.\n         */\n        this.rows = 2;\n        // <input> properties\n        /**\n         * Defines the greatest value in the range of permitted values.\n         *\n         * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#max\n         */\n        this.max = '';\n        /**\n         * The maximum number of characters a user can enter into the text field. Set\n         * to -1 for none.\n         *\n         * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#maxlength\n         */\n        this.maxLength = -1;\n        /**\n         * Defines the most negative value in the range of permitted values.\n         *\n         * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#min\n         */\n        this.min = '';\n        /**\n         * The minimum number of characters a user can enter into the text field. Set\n         * to -1 for none.\n         *\n         * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#minlength\n         */\n        this.minLength = -1;\n        /**\n         * A regular expression that the text field's value must match to pass\n         * constraint validation.\n         *\n         * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#pattern\n         */\n        this.pattern = '';\n        this.placeholder = '';\n        /**\n         * Indicates whether or not a user should be able to edit the text field's\n         * value.\n         *\n         * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#readonly\n         */\n        this.readOnly = false;\n        /**\n         * Returns or sets the element's step attribute, which works with min and max\n         * to limit the increments at which a numeric or date-time value can be set.\n         *\n         * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#step\n         */\n        this.step = '';\n        this.type = 'text';\n        /**\n         * Returns true when the text field has been interacted with. Native\n         * validation errors only display in response to user interactions.\n         */\n        this.dirty = false;\n        this.focused = false;\n        /**\n         * Whether or not a native error has been reported via `reportValidity()`.\n         */\n        this.nativeError = false;\n        /**\n         * The validation message displayed from a native error via\n         * `reportValidity()`.\n         */\n        this.nativeErrorText = '';\n        this.internals = this /* needed for closure */.attachInternals();\n        if (!isServer) {\n            this.addEventListener('click', this.focus);\n            this.addEventListener('focusin', this.handleFocusin);\n            this.addEventListener('focusout', this.handleFocusout);\n        }\n    }\n    /**\n     * Checks the text field's native validation and returns whether or not the\n     * element is valid.\n     *\n     * If invalid, this method will dispatch the `invalid` event.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity\n     *\n     * @return true if the text field is valid, or false if not.\n     */\n    checkValidity() {\n        const { valid } = this.checkValidityAndDispatch();\n        return valid;\n    }\n    /**\n     * Focuses the text field's input text.\n     */\n    focus() {\n        if (this.disabled || this.matches(':focus-within')) {\n            // Don't shift focus from an element within the text field, like an icon\n            // button, to the input when focus is requested.\n            return;\n        }\n        super.focus();\n    }\n    /**\n     * Checks the text field's native validation and returns whether or not the\n     * element is valid.\n     *\n     * If invalid, this method will dispatch the `invalid` event.\n     *\n     * This method will display or clear an error text message equal to the text\n     * field's `validationMessage`, unless the invalid event is canceled.\n     *\n     * Use `setCustomValidity()` to customize the `validationMessage`.\n     *\n     * This method can also be used to re-announce error messages to screen\n     * readers.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/reportValidity\n     *\n     * @return true if the text field is valid, or false if not.\n     */\n    reportValidity() {\n        const { valid, canceled } = this.checkValidityAndDispatch();\n        if (!canceled) {\n            const prevMessage = this.getErrorText();\n            this.nativeError = !valid;\n            this.nativeErrorText = this.validationMessage;\n            if (prevMessage === this.getErrorText()) {\n                this.field?.reannounceError();\n            }\n        }\n        return valid;\n    }\n    /**\n     * Selects all the text in the text field.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select\n     */\n    select() {\n        this.getInputOrTextarea().select();\n    }\n    /**\n     * Sets the text field's native validation error message. This is used to\n     * customize `validationMessage`.\n     *\n     * When the error is not an empty string, the text field is considered invalid\n     * and `validity.customError` will be true.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setCustomValidity\n     *\n     * @param error The error message to display.\n     */\n    setCustomValidity(error) {\n        this.getInputOrTextarea().setCustomValidity(error);\n    }\n    setRangeText(...args) {\n        // Calling setRangeText with 1 vs 3-4 arguments has different behavior.\n        // Use spread syntax and type casting to ensure correct usage.\n        this.getInputOrTextarea().setRangeText(...args);\n        this.value = this.getInputOrTextarea().value;\n    }\n    /**\n     * Sets the start and end positions of a selection in the text field.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n     *\n     * @param start The offset into the text field for the start of the selection.\n     * @param end The offset into the text field for the end of the selection.\n     * @param direction The direction in which the selection is performed.\n     */\n    setSelectionRange(start, end, direction) {\n        this.getInputOrTextarea().setSelectionRange(start, end, direction);\n    }\n    /**\n     * Decrements the value of a numeric type text field by `step` or `n` `step`\n     * number of times.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown\n     *\n     * @param stepDecrement The number of steps to decrement, defaults to 1.\n     */\n    stepDown(stepDecrement) {\n        const input = this.getInput();\n        if (!input) {\n            return;\n        }\n        input.stepDown(stepDecrement);\n        this.value = input.value;\n    }\n    /**\n     * Increments the value of a numeric type text field by `step` or `n` `step`\n     * number of times.\n     *\n     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp\n     *\n     * @param stepIncrement The number of steps to increment, defaults to 1.\n     */\n    stepUp(stepIncrement) {\n        const input = this.getInput();\n        if (!input) {\n            return;\n        }\n        input.stepUp(stepIncrement);\n        this.value = input.value;\n    }\n    /**\n     * Reset the text field to its default value.\n     */\n    reset() {\n        this.dirty = false;\n        this.value = this.getAttribute('value') ?? '';\n        this.nativeError = false;\n        this.nativeErrorText = '';\n    }\n    attributeChangedCallback(attribute, newValue, oldValue) {\n        if (attribute === 'value' && this.dirty) {\n            // After user input, changing the value attribute no longer updates the\n            // text field's value (until reset). This matches native <input> behavior.\n            return;\n        }\n        super.attributeChangedCallback(attribute, newValue, oldValue);\n    }\n    render() {\n        const classes = {\n            'disabled': this.disabled,\n            'error': !this.disabled && this.hasError,\n            'textarea': this.type === 'textarea',\n        };\n        return html `\n       <span class=\"text-field ${classMap(classes)}\">\n         ${this.renderField()}\n       </span>\n     `;\n    }\n    updated(changedProperties) {\n        // Keep changedProperties arg so that subclasses may call it\n        // If a property such as `type` changes and causes the internal <input>\n        // value to change without dispatching an event, re-sync it.\n        const value = this.getInputOrTextarea().value;\n        this.internals.setFormValue(value);\n        if (this.value !== value) {\n            // Note this is typically inefficient in updated() since it schedules\n            // another update. However, it is needed for the <input> to fully render\n            // before checking its value.\n            this.value = value;\n        }\n    }\n    renderField() {\n        return staticHtml `<${this.fieldTag}\n      class=\"field\"\n      count=${this.value.length}\n      ?disabled=${this.disabled}\n      ?error=${this.hasError}\n      error-text=${this.getErrorText()}\n      ?focused=${this.focused}\n      ?has-end=${this.hasTrailingIcon}\n      ?has-start=${this.hasLeadingIcon}\n      label=${this.label}\n      max=${this.maxLength}\n      ?populated=${!!this.value}\n      ?required=${this.required}\n      supporting-text=${this.supportingText}\n    >\n      ${this.renderLeadingIcon()}\n      ${this.renderInputOrTextarea()}\n      ${this.renderTrailingIcon()}\n      <div id=\"description\" slot=\"aria-describedby\"></div>\n    </${this.fieldTag}>`;\n    }\n    renderLeadingIcon() {\n        return html `\n       <span class=\"icon leading\" slot=\"start\">\n         <slot name=\"leadingicon\" @slotchange=${this.handleIconChange}></slot>\n       </span>\n     `;\n    }\n    renderTrailingIcon() {\n        return html `\n       <span class=\"icon trailing\" slot=\"end\">\n         <slot name=\"trailingicon\" @slotchange=${this.handleIconChange}></slot>\n       </span>\n     `;\n    }\n    renderInputOrTextarea() {\n        const style = { direction: this.textDirection };\n        const ariaLabel = this.ariaLabel || this.label || nothing;\n        if (this.type === 'textarea') {\n            return html `\n        <textarea\n          class=\"input\"\n          style=${styleMap(style)}\n          aria-describedby=\"description\"\n          aria-invalid=${this.hasError}\n          aria-label=${ariaLabel}\n          ?disabled=${this.disabled}\n          maxlength=${this.maxLength > -1 ? this.maxLength : nothing}\n          minlength=${this.minLength > -1 ? this.minLength : nothing}\n          placeholder=${this.placeholder || nothing}\n          ?readonly=${this.readOnly}\n          ?required=${this.required}\n          rows=${this.rows}\n          .value=${live(this.value)}\n          @change=${this.redispatchEvent}\n          @input=${this.handleInput}\n          @select=${this.redispatchEvent}\n        ></textarea>\n      `;\n        }\n        const prefix = this.renderPrefix();\n        const suffix = this.renderSuffix();\n        // TODO(b/243805848): remove `as unknown as number` once lit analyzer is\n        // fixed\n        return html `\n      <div class=\"input-wrapper\">\n        ${prefix}\n        <input\n          class=\"input\"\n          style=${styleMap(style)}\n          aria-describedby=\"description\"\n          aria-invalid=${this.hasError}\n          aria-label=${ariaLabel}\n          ?disabled=${this.disabled}\n          max=${(this.max || nothing)}\n          maxlength=${this.maxLength > -1 ? this.maxLength : nothing}\n          min=${(this.min || nothing)}\n          minlength=${this.minLength > -1 ? this.minLength : nothing}\n          pattern=${this.pattern || nothing}\n          placeholder=${this.placeholder || nothing}\n          ?readonly=${this.readOnly}\n          ?required=${this.required}\n          step=${(this.step || nothing)}\n          type=${this.type}\n          .value=${live(this.value)}\n          @change=${this.redispatchEvent}\n          @input=${this.handleInput}\n          @select=${this.redispatchEvent}\n        >\n        ${suffix}\n      </div>\n    `;\n    }\n    renderPrefix() {\n        return this.renderAffix(this.prefixText, /* isSuffix */ false);\n    }\n    renderSuffix() {\n        return this.renderAffix(this.suffixText, /* isSuffix */ true);\n    }\n    renderAffix(text, isSuffix) {\n        if (!text) {\n            return nothing;\n        }\n        const classes = {\n            'suffix': isSuffix,\n            'prefix': !isSuffix,\n        };\n        return html `<span class=\"${classMap(classes)}\">${text}</span>`;\n    }\n    getErrorText() {\n        return this.error ? this.errorText : this.nativeErrorText;\n    }\n    handleFocusin() {\n        this.focused = true;\n    }\n    handleFocusout() {\n        if (this.matches(':focus-within')) {\n            // Changing focus to another child within the text field, like a button\n            return;\n        }\n        this.focused = false;\n    }\n    handleInput(event) {\n        this.dirty = true;\n        this.value = event.target.value;\n        this.redispatchEvent(event);\n    }\n    redispatchEvent(event) {\n        redispatchEvent(this, event);\n    }\n    getInputOrTextarea() {\n        if (!this.inputOrTextarea) {\n            // If the input is not yet defined, synchronously render.\n            // e.g.\n            // const textField = document.createElement('md-outlined-text-field');\n            // document.body.appendChild(textField);\n            // textField.focus(); // synchronously render\n            this.connectedCallback();\n            this.scheduleUpdate();\n        }\n        if (this.isUpdatePending) {\n            // If there are pending updates, synchronously perform them. This ensures\n            // that constraint validation properties (like `required`) are synced\n            // before interacting with input APIs that depend on them.\n            this.scheduleUpdate();\n        }\n        return this.inputOrTextarea;\n    }\n    getInput() {\n        if (this.type === 'textarea') {\n            return null;\n        }\n        return this.getInputOrTextarea();\n    }\n    checkValidityAndDispatch() {\n        const valid = this.getInputOrTextarea().checkValidity();\n        let canceled = false;\n        if (!valid) {\n            canceled = !this.dispatchEvent(new Event('invalid', { cancelable: true }));\n        }\n        return { valid, canceled };\n    }\n    handleIconChange() {\n        this.hasLeadingIcon = this.leadingIcons.length > 0;\n        this.hasTrailingIcon = this.trailingIcons.length > 0;\n    }\n    /** @private */\n    formResetCallback() {\n        this.reset();\n    }\n    /** @private */\n    formStateRestoreCallback(state) {\n        this.value = state;\n    }\n}\n_a = TextField;\n(() => {\n    requestUpdateOnAriaChange(_a);\n})();\n/** @nocollapse */\nTextField.shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };\n/** @nocollapse  */\nTextField.formAssociated = true;\n__decorate([\n    property({ type: Boolean, reflect: true })\n], TextField.prototype, \"disabled\", void 0);\n__decorate([\n    property({ type: Boolean, reflect: true })\n], TextField.prototype, \"error\", void 0);\n__decorate([\n    property({ attribute: 'error-text' })\n], TextField.prototype, \"errorText\", void 0);\n__decorate([\n    property()\n], TextField.prototype, \"label\", void 0);\n__decorate([\n    property({ type: Boolean, reflect: true })\n], TextField.prototype, \"required\", void 0);\n__decorate([\n    property()\n], TextField.prototype, \"value\", void 0);\n__decorate([\n    property({ attribute: 'prefix-text' })\n], TextField.prototype, \"prefixText\", void 0);\n__decorate([\n    property({ attribute: 'suffix-text' })\n], TextField.prototype, \"suffixText\", void 0);\n__decorate([\n    property({ type: Boolean, attribute: 'has-leading-icon' })\n], TextField.prototype, \"hasLeadingIcon\", void 0);\n__decorate([\n    property({ type: Boolean, attribute: 'has-trailing-icon' })\n], TextField.prototype, \"hasTrailingIcon\", void 0);\n__decorate([\n    property({ attribute: 'supporting-text' })\n], TextField.prototype, \"supportingText\", void 0);\n__decorate([\n    property({ attribute: 'text-direction' })\n], TextField.prototype, \"textDirection\", void 0);\n__decorate([\n    property({ type: Number })\n], TextField.prototype, \"rows\", void 0);\n__decorate([\n    property()\n], TextField.prototype, \"max\", void 0);\n__decorate([\n    property({ type: Number })\n], TextField.prototype, \"maxLength\", void 0);\n__decorate([\n    property()\n], TextField.prototype, \"min\", void 0);\n__decorate([\n    property({ type: Number })\n], TextField.prototype, \"minLength\", void 0);\n__decorate([\n    property()\n], TextField.prototype, \"pattern\", void 0);\n__decorate([\n    property({ reflect: true, converter: stringConverter })\n], TextField.prototype, \"placeholder\", void 0);\n__decorate([\n    property({ type: Boolean, reflect: true })\n], TextField.prototype, \"readOnly\", void 0);\n__decorate([\n    property()\n], TextField.prototype, \"step\", void 0);\n__decorate([\n    property({ reflect: true })\n], TextField.prototype, \"type\", void 0);\n__decorate([\n    state()\n], TextField.prototype, \"dirty\", void 0);\n__decorate([\n    state()\n], TextField.prototype, \"focused\", void 0);\n__decorate([\n    state()\n], TextField.prototype, \"nativeError\", void 0);\n__decorate([\n    state()\n], TextField.prototype, \"nativeErrorText\", void 0);\n__decorate([\n    query('.input')\n], TextField.prototype, \"inputOrTextarea\", void 0);\n__decorate([\n    query('.field')\n], TextField.prototype, \"field\", void 0);\n__decorate([\n    queryAssignedElements({ slot: 'leadingicon' })\n], TextField.prototype, \"leadingIcons\", void 0);\n__decorate([\n    queryAssignedElements({ slot: 'trailingicon' })\n], TextField.prototype, \"trailingIcons\", void 0);\n//# sourceMappingURL=text-field.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport '../../field/outlined-field.js';\nimport { literal } from 'lit/static-html.js';\nimport { TextField } from './text-field.js';\n/**\n * An outlined text field component\n */\nexport class OutlinedTextField extends TextField {\n    constructor() {\n        super(...arguments);\n        this.fieldTag = literal `md-outlined-field`;\n    }\n}\n//# sourceMappingURL=outlined-text-field.js.map","/**\n  * @license\n  * Copyright 2022 Google LLC\n  * SPDX-License-Identifier: Apache-2.0\n  */\nimport { css } from 'lit';\nexport const styles = css `:host{display:inline-flex;outline:none;resize:both;-webkit-tap-highlight-color:rgba(0,0,0,0)}.text-field,.field{width:100%}.text-field{display:inline-flex}.field{cursor:text}.disabled .field{cursor:default}.text-field,.textarea .field{resize:inherit}.icon{color:currentColor;display:flex;fill:currentColor}.icon ::slotted(*){display:flex}[hasstart] .icon.leading{font-size:var(--_leading-icon-size);height:var(--_leading-icon-size);width:var(--_leading-icon-size)}[hasend] .icon.trailing{font-size:var(--_trailing-icon-size);height:var(--_trailing-icon-size);width:var(--_trailing-icon-size)}.input-wrapper{display:flex}.input-wrapper>*{all:inherit;padding:0}.input{caret-color:var(--_caret-color);overflow-x:hidden;text-align:inherit}.input::placeholder{color:currentColor;opacity:1}.input::-webkit-calendar-picker-indicator{display:none}@media(forced-colors: active){.input{background-color:Field}}:focus-within .input{caret-color:var(--_focus-caret-color)}.error:focus-within .input{caret-color:var(--_error-focus-caret-color)}.text-field:not(.disabled) .prefix{color:var(--_input-text-prefix-color)}.text-field:not(.disabled) .suffix{color:var(--_input-text-suffix-color)}.text-field:not(.disabled) .input::placeholder{color:var(--_input-text-placeholder-color)}.prefix,.suffix{width:min-content}.prefix{padding-inline-end:var(--_input-text-prefix-trailing-space)}.suffix{padding-inline-start:var(--_input-text-suffix-leading-space)}/*# sourceMappingURL=shared-styles.css.map */\n`;\n//# sourceMappingURL=shared-styles.css.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { __decorate } from \"tslib\";\nimport '../field/outlined-field.js';\nimport { customElement } from 'lit/decorators.js';\nimport { literal } from 'lit/static-html.js';\nimport { styles as outlinedForcedColorsStyles } from './internal/outlined-forced-colors-styles.css.js';\nimport { styles as outlinedStyles } from './internal/outlined-styles.css.js';\nimport { OutlinedTextField } from './internal/outlined-text-field.js';\nimport { styles as sharedStyles } from './internal/shared-styles.css.js';\n/**\n * TODO(b/228525797): Add docs\n * @final\n * @suppress {visibility}\n */\nlet MdOutlinedTextField = class MdOutlinedTextField extends OutlinedTextField {\n    constructor() {\n        super(...arguments);\n        this.fieldTag = literal `md-outlined-field`;\n    }\n};\nMdOutlinedTextField.styles = [sharedStyles, outlinedStyles, outlinedForcedColorsStyles];\nMdOutlinedTextField = __decorate([\n    customElement('md-outlined-text-field')\n], MdOutlinedTextField);\nexport { MdOutlinedTextField };\n//# sourceMappingURL=outlined-text-field.js.map","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * Dummy custom element used for collecting\n * development time usage statistics.\n *\n * @private\n */\nclass Lumo extends HTMLElement {\n  static get version() {\n    return '24.1.4';\n  }\n}\n\ncustomElements.define('vaadin-lumo-styles', Lumo);\n\nexport { Lumo };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n/**\n * @polymerMixin\n */\nexport const ThemePropertyMixin = (superClass) =>\n  class VaadinThemePropertyMixin extends superClass {\n    static get properties() {\n      return {\n        /**\n         * Helper property with theme attribute value facilitating propagation\n         * in shadow DOM.\n         *\n         * Enables the component implementation to propagate the `theme`\n         * attribute value to the sub-components in Shadow DOM by binding\n         * the sub-component's \"theme\" attribute to the `theme` property of\n         * the host.\n         *\n         * **NOTE:** Extending the mixin only provides the property for binding,\n         * and does not make the propagation alone.\n         *\n         * See [Styling Components: Sub-components](https://vaadin.com/docs/latest/styling/styling-components/#sub-components).\n         * page for more information.\n         *\n         * @protected\n         */\n        _theme: {\n          type: String,\n          readOnly: true,\n        },\n      };\n    }\n\n    static get observedAttributes() {\n      return [...super.observedAttributes, 'theme'];\n    }\n\n    /** @protected */\n    attributeChangedCallback(name, oldValue, newValue) {\n      super.attributeChangedCallback(name, oldValue, newValue);\n\n      if (name === 'theme') {\n        this._set_theme(newValue);\n      }\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { css, CSSResult, unsafeCSS } from 'lit';\nimport { ThemePropertyMixin } from './vaadin-theme-property-mixin.js';\n\nexport { css, unsafeCSS };\n\n/**\n * @typedef {Object} Theme\n * @property {string} themeFor\n * @property {CSSResult[]} styles\n * @property {string | string[]} [include]\n * @property {string} [moduleId]\n *\n * @typedef {CSSResult[] | CSSResult} CSSResultGroup\n */\n\n/**\n * @type {Theme[]}\n */\nconst themeRegistry = [];\n\n/**\n * Check if the custom element type has themes applied.\n * @param {Function} elementClass\n * @returns {boolean}\n */\nfunction classHasThemes(elementClass) {\n  return elementClass && Object.prototype.hasOwnProperty.call(elementClass, '__themes');\n}\n\n/**\n * Check if the custom element type has themes applied.\n * @param {string} tagName\n * @returns {boolean}\n */\nfunction hasThemes(tagName) {\n  return classHasThemes(customElements.get(tagName));\n}\n\n/**\n * Flattens the styles into a single array of styles.\n * @param {CSSResultGroup} styles\n * @param {CSSResult[]} result\n * @returns {CSSResult[]}\n */\nfunction flattenStyles(styles = []) {\n  return [styles].flat(Infinity).filter((style) => {\n    if (style instanceof CSSResult) {\n      return true;\n    }\n    console.warn('An item in styles is not of type CSSResult. Use `unsafeCSS` or `css`.');\n    return false;\n  });\n}\n\n/**\n * Registers CSS styles for a component type. Make sure to register the styles before\n * the first instance of a component of the type is attached to DOM.\n *\n * @param {string} themeFor The local/tag name of the component type to register the styles for\n * @param {CSSResultGroup} styles The CSS style rules to be registered for the component type\n * matching themeFor and included in the local scope of each component instance\n * @param {{moduleId?: string, include?: string | string[]}} options Additional options\n * @return {void}\n */\nexport function registerStyles(themeFor, styles, options = {}) {\n  if (themeFor) {\n    if (hasThemes(themeFor)) {\n      console.warn(`The custom element definition for \"${themeFor}\"\n      was finalized before a style module was registered.\n      Make sure to add component specific style modules before\n      importing the corresponding custom element.`);\n    }\n  }\n\n  styles = flattenStyles(styles);\n\n  if (window.Vaadin && window.Vaadin.styleModules) {\n    window.Vaadin.styleModules.registerStyles(themeFor, styles, options);\n  } else {\n    themeRegistry.push({\n      themeFor,\n      styles,\n      include: options.include,\n      moduleId: options.moduleId,\n    });\n  }\n}\n\n/**\n * Returns all registered themes. By default the themeRegistry is returned as is.\n * In case the style-modules adapter is imported, the themes are obtained from there instead\n * @returns {Theme[]}\n */\nfunction getAllThemes() {\n  if (window.Vaadin && window.Vaadin.styleModules) {\n    return window.Vaadin.styleModules.getAllThemes();\n  }\n  return themeRegistry;\n}\n\n/**\n * Returns true if the themeFor string matches the tag name\n * @param {string} themeFor\n * @param {string} tagName\n * @returns {boolean}\n */\nfunction matchesThemeFor(themeFor, tagName) {\n  return (themeFor || '').split(' ').some((themeForToken) => {\n    return new RegExp(`^${themeForToken.split('*').join('.*')}$`, 'u').test(tagName);\n  });\n}\n\n/**\n * Maps the moduleName to an include priority number which is used for\n * determining the order in which styles are applied.\n * @param {string} moduleName\n * @returns {number}\n */\nfunction getIncludePriority(moduleName = '') {\n  let includePriority = 0;\n  if (moduleName.startsWith('lumo-') || moduleName.startsWith('material-')) {\n    includePriority = 1;\n  } else if (moduleName.startsWith('vaadin-')) {\n    includePriority = 2;\n  }\n  return includePriority;\n}\n\n/**\n * Gets an array of CSSResults matching the include property of the theme.\n * @param {Theme} theme\n * @returns {CSSResult[]}\n */\nfunction getIncludedStyles(theme) {\n  const includedStyles = [];\n  if (theme.include) {\n    [].concat(theme.include).forEach((includeModuleId) => {\n      const includedTheme = getAllThemes().find((s) => s.moduleId === includeModuleId);\n      if (includedTheme) {\n        includedStyles.push(...getIncludedStyles(includedTheme), ...includedTheme.styles);\n      } else {\n        console.warn(`Included moduleId ${includeModuleId} not found in style registry`);\n      }\n    }, theme.styles);\n  }\n  return includedStyles;\n}\n\n/**\n * Includes the styles to the template.\n * @param {CSSResult[]} styles\n * @param {HTMLTemplateElement} template\n */\nfunction addStylesToTemplate(styles, template) {\n  const styleEl = document.createElement('style');\n  styleEl.innerHTML = styles.map((style) => style.cssText).join('\\n');\n  template.content.appendChild(styleEl);\n}\n\n/**\n * Returns an array of themes that should be used for styling a component matching\n * the tag name. The array is sorted by the include order.\n * @param {string} tagName\n * @returns {Theme[]}\n */\nfunction getThemes(tagName) {\n  const defaultModuleName = `${tagName}-default-theme`;\n\n  const themes = getAllThemes()\n    // Filter by matching themeFor properties\n    .filter((theme) => theme.moduleId !== defaultModuleName && matchesThemeFor(theme.themeFor, tagName))\n    .map((theme) => ({\n      ...theme,\n      // Prepend styles from included themes\n      styles: [...getIncludedStyles(theme), ...theme.styles],\n      // Map moduleId to includePriority\n      includePriority: getIncludePriority(theme.moduleId),\n    }))\n    // Sort by includePriority\n    .sort((themeA, themeB) => themeB.includePriority - themeA.includePriority);\n\n  if (themes.length > 0) {\n    return themes;\n  }\n  // No theme modules found, return the default module if it exists\n  return getAllThemes().filter((theme) => theme.moduleId === defaultModuleName);\n}\n\n/**\n * @polymerMixin\n * @mixes ThemePropertyMixin\n */\nexport const ThemableMixin = (superClass) =>\n  class VaadinThemableMixin extends ThemePropertyMixin(superClass) {\n    /**\n     * Covers PolymerElement based component styling\n     * @protected\n     */\n    static finalize() {\n      super.finalize();\n\n      // Make sure not to run the logic intended for PolymerElement when LitElement is used.\n      if (this.elementStyles) {\n        return;\n      }\n\n      const template = this.prototype._template;\n      if (!template || classHasThemes(this)) {\n        return;\n      }\n\n      addStylesToTemplate(this.getStylesForThis(), template);\n    }\n\n    /**\n     * Covers LitElement based component styling\n     *\n     * @protected\n     */\n    static finalizeStyles(styles) {\n      // The \"styles\" object originates from the \"static get styles()\" function of\n      // a LitElement based component. The theme styles are added after it\n      // so that they can override the component styles.\n      const themeStyles = this.getStylesForThis();\n      return styles ? [...super.finalizeStyles(styles), ...themeStyles] : themeStyles;\n    }\n\n    /**\n     * Get styles for the component type\n     *\n     * @private\n     */\n    static getStylesForThis() {\n      const parent = Object.getPrototypeOf(this.prototype);\n      const inheritedThemes = (parent ? parent.constructor.__themes : []) || [];\n      this.__themes = [...inheritedThemes, ...getThemes(this.is)];\n      const themeStyles = this.__themes.flatMap((theme) => theme.styles);\n      // Remove duplicates\n      return themeStyles.filter((style, index) => index === themeStyles.lastIndexOf(style));\n    }\n  };\n\nexport { themeRegistry as __themeRegistry };\n","import { addGlobalThemeStyles } from '@vaadin/vaadin-themable-mixin/register-styles.js';\n\nexport const addLumoGlobalStyles = (id, ...styles) => {\n  addGlobalThemeStyles(`lumo-${id}`, styles);\n};\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nexport { registerStyles, css, unsafeCSS } from './vaadin-themable-mixin.js';\n\n/**\n * This is for use internally by Lumo and Material styles.\n *\n * @param {string} id the id to set on the created element, only for informational purposes\n * @param  {CSSResultGroup[]} styles the styles to add\n */\nexport const addGlobalThemeStyles = (id, ...styles) => {\n  const styleTag = document.createElement('style');\n  styleTag.id = id;\n  styleTag.textContent = styles\n    .map((style) => style.toString())\n    .join('\\n')\n    .replace(':host', 'html');\n\n  document.head.insertAdjacentElement('afterbegin', styleTag);\n};\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport './version.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { addLumoGlobalStyles } from './global.js';\n\nconst colorBase = css`\n  :host {\n    /* Base (background) */\n    --lumo-base-color: #fff;\n\n    /* Tint */\n    --lumo-tint-5pct: hsla(0, 0%, 100%, 0.3);\n    --lumo-tint-10pct: hsla(0, 0%, 100%, 0.37);\n    --lumo-tint-20pct: hsla(0, 0%, 100%, 0.44);\n    --lumo-tint-30pct: hsla(0, 0%, 100%, 0.5);\n    --lumo-tint-40pct: hsla(0, 0%, 100%, 0.57);\n    --lumo-tint-50pct: hsla(0, 0%, 100%, 0.64);\n    --lumo-tint-60pct: hsla(0, 0%, 100%, 0.7);\n    --lumo-tint-70pct: hsla(0, 0%, 100%, 0.77);\n    --lumo-tint-80pct: hsla(0, 0%, 100%, 0.84);\n    --lumo-tint-90pct: hsla(0, 0%, 100%, 0.9);\n    --lumo-tint: #fff;\n\n    /* Shade */\n    --lumo-shade-5pct: hsla(214, 61%, 25%, 0.05);\n    --lumo-shade-10pct: hsla(214, 57%, 24%, 0.1);\n    --lumo-shade-20pct: hsla(214, 53%, 23%, 0.16);\n    --lumo-shade-30pct: hsla(214, 50%, 22%, 0.26);\n    --lumo-shade-40pct: hsla(214, 47%, 21%, 0.38);\n    --lumo-shade-50pct: hsla(214, 45%, 20%, 0.52);\n    --lumo-shade-60pct: hsla(214, 43%, 19%, 0.6);\n    --lumo-shade-70pct: hsla(214, 42%, 18%, 0.69);\n    --lumo-shade-80pct: hsla(214, 41%, 17%, 0.83);\n    --lumo-shade-90pct: hsla(214, 40%, 16%, 0.94);\n    --lumo-shade: hsl(214, 35%, 15%);\n\n    /* Contrast */\n    --lumo-contrast-5pct: var(--lumo-shade-5pct);\n    --lumo-contrast-10pct: var(--lumo-shade-10pct);\n    --lumo-contrast-20pct: var(--lumo-shade-20pct);\n    --lumo-contrast-30pct: var(--lumo-shade-30pct);\n    --lumo-contrast-40pct: var(--lumo-shade-40pct);\n    --lumo-contrast-50pct: var(--lumo-shade-50pct);\n    --lumo-contrast-60pct: var(--lumo-shade-60pct);\n    --lumo-contrast-70pct: var(--lumo-shade-70pct);\n    --lumo-contrast-80pct: var(--lumo-shade-80pct);\n    --lumo-contrast-90pct: var(--lumo-shade-90pct);\n    --lumo-contrast: var(--lumo-shade);\n\n    /* Text */\n    --lumo-header-text-color: var(--lumo-contrast);\n    --lumo-body-text-color: var(--lumo-contrast-90pct);\n    --lumo-secondary-text-color: var(--lumo-contrast-70pct);\n    --lumo-tertiary-text-color: var(--lumo-contrast-50pct);\n    --lumo-disabled-text-color: var(--lumo-contrast-30pct);\n\n    /* Primary */\n    --lumo-primary-color: hsl(214, 100%, 48%);\n    --lumo-primary-color-50pct: hsla(214, 100%, 49%, 0.76);\n    --lumo-primary-color-10pct: hsla(214, 100%, 60%, 0.13);\n    --lumo-primary-text-color: hsl(214, 100%, 43%);\n    --lumo-primary-contrast-color: #fff;\n\n    /* Error */\n    --lumo-error-color: hsl(3, 85%, 48%);\n    --lumo-error-color-50pct: hsla(3, 85%, 49%, 0.5);\n    --lumo-error-color-10pct: hsla(3, 85%, 49%, 0.1);\n    --lumo-error-text-color: hsl(3, 89%, 42%);\n    --lumo-error-contrast-color: #fff;\n\n    /* Success */\n    --lumo-success-color: hsl(145, 72%, 30%);\n    --lumo-success-color-50pct: hsla(145, 72%, 31%, 0.5);\n    --lumo-success-color-10pct: hsla(145, 72%, 31%, 0.1);\n    --lumo-success-text-color: hsl(145, 85%, 25%);\n    --lumo-success-contrast-color: #fff;\n\n    /* Warning */\n    --lumo-warning-color: hsl(48, 100%, 50%);\n    --lumo-warning-color-10pct: hsla(48, 100%, 50%, 0.25);\n    --lumo-warning-text-color: hsl(32, 100%, 30%);\n    --lumo-warning-contrast-color: var(--lumo-shade-90pct);\n  }\n\n  /* forced-colors mode adjustments */\n  @media (forced-colors: active) {\n    html {\n      --lumo-disabled-text-color: GrayText;\n    }\n  }\n`;\n\naddLumoGlobalStyles('color-props', colorBase);\n\nconst color = css`\n  [theme~='dark'] {\n    /* Base (background) */\n    --lumo-base-color: hsl(214, 35%, 21%);\n\n    /* Tint */\n    --lumo-tint-5pct: hsla(214, 65%, 85%, 0.06);\n    --lumo-tint-10pct: hsla(214, 60%, 80%, 0.14);\n    --lumo-tint-20pct: hsla(214, 64%, 82%, 0.23);\n    --lumo-tint-30pct: hsla(214, 69%, 84%, 0.32);\n    --lumo-tint-40pct: hsla(214, 73%, 86%, 0.41);\n    --lumo-tint-50pct: hsla(214, 78%, 88%, 0.5);\n    --lumo-tint-60pct: hsla(214, 82%, 90%, 0.58);\n    --lumo-tint-70pct: hsla(214, 87%, 92%, 0.69);\n    --lumo-tint-80pct: hsla(214, 91%, 94%, 0.8);\n    --lumo-tint-90pct: hsla(214, 96%, 96%, 0.9);\n    --lumo-tint: hsl(214, 100%, 98%);\n\n    /* Shade */\n    --lumo-shade-5pct: hsla(214, 0%, 0%, 0.07);\n    --lumo-shade-10pct: hsla(214, 4%, 2%, 0.15);\n    --lumo-shade-20pct: hsla(214, 8%, 4%, 0.23);\n    --lumo-shade-30pct: hsla(214, 12%, 6%, 0.32);\n    --lumo-shade-40pct: hsla(214, 16%, 8%, 0.41);\n    --lumo-shade-50pct: hsla(214, 20%, 10%, 0.5);\n    --lumo-shade-60pct: hsla(214, 24%, 12%, 0.6);\n    --lumo-shade-70pct: hsla(214, 28%, 13%, 0.7);\n    --lumo-shade-80pct: hsla(214, 32%, 13%, 0.8);\n    --lumo-shade-90pct: hsla(214, 33%, 13%, 0.9);\n    --lumo-shade: hsl(214, 33%, 13%);\n\n    /* Contrast */\n    --lumo-contrast-5pct: var(--lumo-tint-5pct);\n    --lumo-contrast-10pct: var(--lumo-tint-10pct);\n    --lumo-contrast-20pct: var(--lumo-tint-20pct);\n    --lumo-contrast-30pct: var(--lumo-tint-30pct);\n    --lumo-contrast-40pct: var(--lumo-tint-40pct);\n    --lumo-contrast-50pct: var(--lumo-tint-50pct);\n    --lumo-contrast-60pct: var(--lumo-tint-60pct);\n    --lumo-contrast-70pct: var(--lumo-tint-70pct);\n    --lumo-contrast-80pct: var(--lumo-tint-80pct);\n    --lumo-contrast-90pct: var(--lumo-tint-90pct);\n    --lumo-contrast: var(--lumo-tint);\n\n    /* Text */\n    --lumo-header-text-color: var(--lumo-contrast);\n    --lumo-body-text-color: var(--lumo-contrast-90pct);\n    --lumo-secondary-text-color: var(--lumo-contrast-70pct);\n    --lumo-tertiary-text-color: var(--lumo-contrast-50pct);\n    --lumo-disabled-text-color: var(--lumo-contrast-30pct);\n\n    /* Primary */\n    --lumo-primary-color: hsl(214, 90%, 48%);\n    --lumo-primary-color-50pct: hsla(214, 90%, 70%, 0.69);\n    --lumo-primary-color-10pct: hsla(214, 90%, 55%, 0.13);\n    --lumo-primary-text-color: hsl(214, 90%, 77%);\n    --lumo-primary-contrast-color: #fff;\n\n    /* Error */\n    --lumo-error-color: hsl(3, 79%, 49%);\n    --lumo-error-color-50pct: hsla(3, 75%, 62%, 0.5);\n    --lumo-error-color-10pct: hsla(3, 75%, 62%, 0.14);\n    --lumo-error-text-color: hsl(3, 100%, 80%);\n\n    /* Success */\n    --lumo-success-color: hsl(145, 72%, 30%);\n    --lumo-success-color-50pct: hsla(145, 92%, 51%, 0.5);\n    --lumo-success-color-10pct: hsla(145, 92%, 51%, 0.1);\n    --lumo-success-text-color: hsl(145, 85%, 46%);\n\n    /* Warning */\n    --lumo-warning-color: hsl(43, 100%, 48%);\n    --lumo-warning-color-10pct: hsla(40, 100%, 50%, 0.2);\n    --lumo-warning-text-color: hsl(45, 100%, 60%);\n    --lumo-warning-contrast-color: var(--lumo-shade-90pct);\n  }\n\n  html {\n    color: var(--lumo-body-text-color);\n    background-color: var(--lumo-base-color);\n    color-scheme: light;\n  }\n\n  [theme~='dark'] {\n    color: var(--lumo-body-text-color);\n    background-color: var(--lumo-base-color);\n    color-scheme: dark;\n  }\n\n  h1,\n  h2,\n  h3,\n  h4,\n  h5,\n  h6 {\n    color: var(--lumo-header-text-color);\n  }\n\n  a:where(:any-link) {\n    color: var(--lumo-primary-text-color);\n  }\n\n  a:not(:any-link) {\n    color: var(--lumo-disabled-text-color);\n  }\n\n  blockquote {\n    color: var(--lumo-secondary-text-color);\n  }\n\n  code,\n  pre {\n    background-color: var(--lumo-contrast-10pct);\n    border-radius: var(--lumo-border-radius-m);\n  }\n`;\n\nregisterStyles('', color, { moduleId: 'lumo-color' });\n\nexport { colorBase, color };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport './version.js';\nimport { css } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { addLumoGlobalStyles } from './global.js';\n\nconst sizing = css`\n  :host {\n    --lumo-size-xs: 1.625rem;\n    --lumo-size-s: 1.875rem;\n    --lumo-size-m: 2.25rem;\n    --lumo-size-l: 2.75rem;\n    --lumo-size-xl: 3.5rem;\n\n    /* Icons */\n    --lumo-icon-size-s: 1.25em;\n    --lumo-icon-size-m: 1.5em;\n    --lumo-icon-size-l: 2.25em;\n    /* For backwards compatibility */\n    --lumo-icon-size: var(--lumo-icon-size-m);\n  }\n`;\n\naddLumoGlobalStyles('sizing-props', sizing);\n\nexport { sizing };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport './version.js';\nimport { css } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { addLumoGlobalStyles } from './global.js';\n\nconst style = css`\n  :host {\n    /* Border radius */\n    --lumo-border-radius-s: 0.25em; /* Checkbox, badge, date-picker year indicator, etc */\n    --lumo-border-radius-m: var(--lumo-border-radius, 0.25em); /* Button, text field, menu overlay, etc */\n    --lumo-border-radius-l: 0.5em; /* Dialog, notification, etc */\n\n    /* Shadow */\n    --lumo-box-shadow-xs: 0 1px 4px -1px var(--lumo-shade-50pct);\n    --lumo-box-shadow-s: 0 2px 4px -1px var(--lumo-shade-20pct), 0 3px 12px -1px var(--lumo-shade-30pct);\n    --lumo-box-shadow-m: 0 2px 6px -1px var(--lumo-shade-20pct), 0 8px 24px -4px var(--lumo-shade-40pct);\n    --lumo-box-shadow-l: 0 3px 18px -2px var(--lumo-shade-20pct), 0 12px 48px -6px var(--lumo-shade-40pct);\n    --lumo-box-shadow-xl: 0 4px 24px -3px var(--lumo-shade-20pct), 0 18px 64px -8px var(--lumo-shade-40pct);\n\n    /* Clickable element cursor */\n    --lumo-clickable-cursor: default;\n  }\n`;\n\n/**\n * Default values for component-specific custom properties.\n */\nconst globals = css`\n  html {\n    --vaadin-checkbox-size: calc(var(--lumo-size-m) / 2);\n    --vaadin-radio-button-size: calc(var(--lumo-size-m) / 2);\n    --vaadin-input-field-border-radius: var(--lumo-border-radius-m);\n  }\n`;\n\naddLumoGlobalStyles('style-props', style);\n\nexport { globals, style };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport './version.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { addLumoGlobalStyles } from './global.js';\n\nconst font = css`\n  :host {\n    /* prettier-ignore */\n    --lumo-font-family: -apple-system, BlinkMacSystemFont, 'Roboto', 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';\n\n    /* Font sizes */\n    --lumo-font-size-xxs: 0.75rem;\n    --lumo-font-size-xs: 0.8125rem;\n    --lumo-font-size-s: 0.875rem;\n    --lumo-font-size-m: 1rem;\n    --lumo-font-size-l: 1.125rem;\n    --lumo-font-size-xl: 1.375rem;\n    --lumo-font-size-xxl: 1.75rem;\n    --lumo-font-size-xxxl: 2.5rem;\n\n    /* Line heights */\n    --lumo-line-height-xs: 1.25;\n    --lumo-line-height-s: 1.375;\n    --lumo-line-height-m: 1.625;\n  }\n`;\n\nconst typography = css`\n  body,\n  :host {\n    font-family: var(--lumo-font-family);\n    font-size: var(--lumo-font-size-m);\n    line-height: var(--lumo-line-height-m);\n    -webkit-text-size-adjust: 100%;\n    -webkit-font-smoothing: antialiased;\n    -moz-osx-font-smoothing: grayscale;\n  }\n\n  small,\n  [theme~='font-size-s'] {\n    font-size: var(--lumo-font-size-s);\n    line-height: var(--lumo-line-height-s);\n  }\n\n  [theme~='font-size-xs'] {\n    font-size: var(--lumo-font-size-xs);\n    line-height: var(--lumo-line-height-xs);\n  }\n\n  :where(h1, h2, h3, h4, h5, h6) {\n    font-weight: 600;\n    line-height: var(--lumo-line-height-xs);\n    margin-block: 0;\n  }\n\n  :where(h1) {\n    font-size: var(--lumo-font-size-xxxl);\n  }\n\n  :where(h2) {\n    font-size: var(--lumo-font-size-xxl);\n  }\n\n  :where(h3) {\n    font-size: var(--lumo-font-size-xl);\n  }\n\n  :where(h4) {\n    font-size: var(--lumo-font-size-l);\n  }\n\n  :where(h5) {\n    font-size: var(--lumo-font-size-m);\n  }\n\n  :where(h6) {\n    font-size: var(--lumo-font-size-xs);\n    text-transform: uppercase;\n    letter-spacing: 0.03em;\n  }\n\n  p,\n  blockquote {\n    margin-top: 0.5em;\n    margin-bottom: 0.75em;\n  }\n\n  a {\n    text-decoration: none;\n  }\n\n  a:where(:any-link):hover {\n    text-decoration: underline;\n  }\n\n  hr {\n    display: block;\n    align-self: stretch;\n    height: 1px;\n    border: 0;\n    padding: 0;\n    margin: var(--lumo-space-s) calc(var(--lumo-border-radius-m) / 2);\n    background-color: var(--lumo-contrast-10pct);\n  }\n\n  blockquote {\n    border-left: 2px solid var(--lumo-contrast-30pct);\n  }\n\n  b,\n  strong {\n    font-weight: 600;\n  }\n\n  /* RTL specific styles */\n  blockquote[dir='rtl'] {\n    border-left: none;\n    border-right: 2px solid var(--lumo-contrast-30pct);\n  }\n`;\n\nregisterStyles('', typography, { moduleId: 'lumo-typography' });\naddLumoGlobalStyles('typography-props', font);\n\nexport { font, typography };\n","import '@vaadin/vaadin-lumo-styles/color.js';\nimport '@vaadin/vaadin-lumo-styles/sizing.js';\nimport '@vaadin/vaadin-lumo-styles/style.js';\nimport '@vaadin/vaadin-lumo-styles/typography.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles(\n  'vaadin-input-container',\n  css`\n    :host {\n      background-color: var(--lumo-contrast-10pct);\n      padding: 0 calc(0.375em + var(--_input-container-radius) / 4 - 1px);\n      font-weight: 500;\n      line-height: 1;\n      position: relative;\n      cursor: text;\n      box-sizing: border-box;\n      border-radius:\n        /* See https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius#syntax */\n        var(--vaadin-input-field-top-start-radius, var(--_input-container-radius))\n        var(--vaadin-input-field-top-end-radius, var(--_input-container-radius))\n        var(--vaadin-input-field-bottom-end-radius, var(--_input-container-radius))\n        var(--vaadin-input-field-bottom-start-radius, var(--_input-container-radius));\n      /* Fallback */\n      --_input-container-radius: var(--vaadin-input-field-border-radius, var(--lumo-border-radius-m));\n      /* Default field border color */\n      --_input-border-color: var(--vaadin-input-field-border-color, var(--lumo-contrast-50pct));\n    }\n\n    :host([dir='rtl']) {\n      border-radius:\n        /* Don't use logical props, see https://github.com/vaadin/vaadin-time-picker/issues/145 */\n        var(--vaadin-input-field-top-end-radius, var(--_input-container-radius))\n        var(--vaadin-input-field-top-start-radius, var(--_input-container-radius))\n        var(--vaadin-input-field-bottom-start-radius, var(--_input-container-radius))\n        var(--vaadin-input-field-bottom-end-radius, var(--_input-container-radius));\n    }\n\n    /* Used for hover and activation effects */\n    :host::after {\n      content: '';\n      position: absolute;\n      top: 0;\n      right: 0;\n      bottom: 0;\n      left: 0;\n      border-radius: inherit;\n      pointer-events: none;\n      background-color: var(--lumo-contrast-50pct);\n      opacity: 0;\n      transition: transform 0.15s, opacity 0.2s;\n      transform-origin: 100% 0;\n    }\n\n    ::slotted(:not([slot$='fix'])) {\n      cursor: inherit;\n      min-height: var(--lumo-text-field-size, var(--lumo-size-m));\n      padding: 0 0.25em;\n      --_lumo-text-field-overflow-mask-image: linear-gradient(to left, transparent, #000 1.25em);\n      -webkit-mask-image: var(--_lumo-text-field-overflow-mask-image);\n      mask-image: var(--_lumo-text-field-overflow-mask-image);\n    }\n\n    /* Read-only */\n    :host([readonly]) {\n      color: var(--lumo-secondary-text-color);\n      background-color: transparent;\n      cursor: default;\n    }\n\n    :host([readonly])::after {\n      background-color: transparent;\n      opacity: 1;\n      border: 1px dashed var(--lumo-contrast-30pct);\n    }\n\n    /* Disabled */\n    :host([disabled]) {\n      background-color: var(--lumo-contrast-5pct);\n    }\n\n    :host([disabled]) ::slotted(*) {\n      color: var(--lumo-disabled-text-color);\n      -webkit-text-fill-color: var(--lumo-disabled-text-color);\n    }\n\n    /* Invalid */\n    :host([invalid]) {\n      background-color: var(--lumo-error-color-10pct);\n    }\n\n    :host([invalid])::after {\n      background-color: var(--lumo-error-color-50pct);\n    }\n\n    /* Slotted icons */\n    ::slotted(vaadin-icon) {\n      color: var(--lumo-contrast-60pct);\n      width: var(--lumo-icon-size-m);\n      height: var(--lumo-icon-size-m);\n    }\n\n    /* Vaadin icons are based on a 16x16 grid (unlike Lumo and Material icons with 24x24), so they look too big by default */\n    ::slotted(vaadin-icon[icon^='vaadin:']) {\n      padding: 0.25em;\n      box-sizing: border-box !important;\n    }\n\n    /* Text align */\n    :host([dir='rtl']) ::slotted(:not([slot$='fix'])) {\n      --_lumo-text-field-overflow-mask-image: linear-gradient(to right, transparent, #000 1.25em);\n    }\n\n    @-moz-document url-prefix() {\n      :host([dir='rtl']) ::slotted(:not([slot$='fix'])) {\n        mask-image: var(--_lumo-text-field-overflow-mask-image);\n      }\n    }\n\n    :host([theme~='align-left']) ::slotted(:not([slot$='fix'])) {\n      text-align: start;\n      --_lumo-text-field-overflow-mask-image: none;\n    }\n\n    :host([theme~='align-center']) ::slotted(:not([slot$='fix'])) {\n      text-align: center;\n      --_lumo-text-field-overflow-mask-image: none;\n    }\n\n    :host([theme~='align-right']) ::slotted(:not([slot$='fix'])) {\n      text-align: end;\n      --_lumo-text-field-overflow-mask-image: none;\n    }\n\n    @-moz-document url-prefix() {\n      /* Firefox is smart enough to align overflowing text to right */\n      :host([theme~='align-right']) ::slotted(:not([slot$='fix'])) {\n        --_lumo-text-field-overflow-mask-image: linear-gradient(to right, transparent 0.25em, #000 1.5em);\n      }\n    }\n\n    @-moz-document url-prefix() {\n      /* Firefox is smart enough to align overflowing text to right */\n      :host([theme~='align-left']) ::slotted(:not([slot$='fix'])) {\n        --_lumo-text-field-overflow-mask-image: linear-gradient(to left, transparent 0.25em, #000 1.5em);\n      }\n    }\n\n    /* RTL specific styles */\n    :host([dir='rtl'])::after {\n      transform-origin: 0% 0;\n    }\n\n    :host([theme~='align-left'][dir='rtl']) ::slotted(:not([slot$='fix'])) {\n      --_lumo-text-field-overflow-mask-image: none;\n    }\n\n    :host([theme~='align-center'][dir='rtl']) ::slotted(:not([slot$='fix'])) {\n      --_lumo-text-field-overflow-mask-image: none;\n    }\n\n    :host([theme~='align-right'][dir='rtl']) ::slotted(:not([slot$='fix'])) {\n      --_lumo-text-field-overflow-mask-image: none;\n    }\n\n    @-moz-document url-prefix() {\n      /* Firefox is smart enough to align overflowing text to right */\n      :host([theme~='align-right'][dir='rtl']) ::slotted(:not([slot$='fix'])) {\n        --_lumo-text-field-overflow-mask-image: linear-gradient(to right, transparent 0.25em, #000 1.5em);\n      }\n    }\n\n    @-moz-document url-prefix() {\n      /* Firefox is smart enough to align overflowing text to right */\n      :host([theme~='align-left'][dir='rtl']) ::slotted(:not([slot$='fix'])) {\n        --_lumo-text-field-overflow-mask-image: linear-gradient(to left, transparent 0.25em, #000 1.5em);\n      }\n    }\n  `,\n  { moduleId: 'lumo-input-container' },\n);\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\n/* eslint-disable no-unused-vars */\n/**\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is replaced by the munged name for object[property]\n * We cannot alias this function, so we have to use a small shim that has the same behavior when not compiling.\n *\n * @param {?} prop Property name\n * @param {*} obj Reference object\n * @return {string} Potentially renamed property name\n */\nwindow.JSCompiler_renameProperty = function(prop, obj) {\n  return prop;\n};\n/* eslint-enable */\n\nexport {};\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\n\nlet CSS_URL_RX = /(url\\()([^)]*)(\\))/g;\nlet ABS_URL = /(^\\/[^\\/])|(^#)|(^[\\w-\\d]*:)/;\nlet workingURL;\nlet resolveDoc;\n/**\n * Resolves the given URL against the provided `baseUri'.\n *\n * Note that this function performs no resolution for URLs that start\n * with `/` (absolute URLs) or `#` (hash identifiers).  For general purpose\n * URL resolution, use `window.URL`.\n *\n * @param {string} url Input URL to resolve\n * @param {?string=} baseURI Base URI to resolve the URL against\n * @return {string} resolved URL\n */\nexport function resolveUrl(url, baseURI) {\n  if (url && ABS_URL.test(url)) {\n    return url;\n  }\n  if (url === '//') {\n    return url;\n  }\n  // Lazy feature detection.\n  if (workingURL === undefined) {\n    workingURL = false;\n    try {\n      const u = new URL('b', 'http://a');\n      u.pathname = 'c%20d';\n      workingURL = (u.href === 'http://a/c%20d');\n    } catch (e) {\n      // silently fail\n    }\n  }\n  if (!baseURI) {\n    baseURI = document.baseURI || window.location.href;\n  }\n  if (workingURL) {\n    try {\n      return (new URL(url, baseURI)).href;\n    } catch (e) {\n      // Bad url or baseURI structure. Do not attempt to resolve.\n      return url;\n    }\n  }\n  // Fallback to creating an anchor into a disconnected document.\n  if (!resolveDoc) {\n    resolveDoc = document.implementation.createHTMLDocument('temp');\n    resolveDoc.base = resolveDoc.createElement('base');\n    resolveDoc.head.appendChild(resolveDoc.base);\n    resolveDoc.anchor = resolveDoc.createElement('a');\n    resolveDoc.body.appendChild(resolveDoc.anchor);\n  }\n  resolveDoc.base.href = baseURI;\n  resolveDoc.anchor.href = url;\n  return resolveDoc.anchor.href || url;\n\n}\n\n/**\n * Resolves any relative URL's in the given CSS text against the provided\n * `ownerDocument`'s `baseURI`.\n *\n * @param {string} cssText CSS text to process\n * @param {string} baseURI Base URI to resolve the URL against\n * @return {string} Processed CSS text with resolved URL's\n */\nexport function resolveCss(cssText, baseURI) {\n  return cssText.replace(CSS_URL_RX, function(m, pre, url, post) {\n    return pre + '\\'' +\n      resolveUrl(url.replace(/[\"']/g, ''), baseURI) +\n      '\\'' + post;\n  });\n}\n\n/**\n * Returns a path from a given `url`. The path includes the trailing\n * `/` from the url.\n *\n * @param {string} url Input URL to transform\n * @return {string} resolved path\n */\nexport function pathFromUrl(url) {\n  return url.substring(0, url.lastIndexOf('/') + 1);\n}\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\nimport { pathFromUrl } from './resolve-url.js';\nexport const useShadow = !(window.ShadyDOM) || !(window.ShadyDOM.inUse);\nexport const useNativeCSSProperties = Boolean(!window.ShadyCSS || window.ShadyCSS.nativeCss);\nexport const useNativeCustomElements = !(window.customElements.polyfillWrapFlushCallback);\nexport const supportsAdoptingStyleSheets = useShadow &&\n    ('adoptedStyleSheets' in Document.prototype) &&\n    ('replaceSync' in CSSStyleSheet.prototype) &&\n    // Since spec may change, feature detect exact API we need\n    (() => {\n      try {\n        const sheet = new CSSStyleSheet();\n        sheet.replaceSync('');\n        const host = document.createElement('div');\n        host.attachShadow({mode: 'open'});\n        host.shadowRoot.adoptedStyleSheets = [sheet];\n        return (host.shadowRoot.adoptedStyleSheets[0] === sheet);\n      } catch(e) {\n        return false;\n      }\n    })();\n\n/**\n * Globally settable property that is automatically assigned to\n * `ElementMixin` instances, useful for binding in templates to\n * make URL's relative to an application's root.  Defaults to the main\n * document URL, but can be overridden by users.  It may be useful to set\n * `rootPath` to provide a stable application mount path when\n * using client side routing.\n */\nexport let rootPath = window.Polymer && window.Polymer.rootPath ||\n  pathFromUrl(document.baseURI || window.location.href);\n\n/**\n * Sets the global rootPath property used by `ElementMixin` and\n * available via `rootPath`.\n *\n * @param {string} path The new root path\n * @return {void}\n */\nexport const setRootPath = function(path) {\n  rootPath = path;\n};\n\n/**\n * A global callback used to sanitize any value before inserting it into the DOM.\n * The callback signature is:\n *\n *  function sanitizeDOMValue(value, name, type, node) { ... }\n *\n * Where:\n *\n * `value` is the value to sanitize.\n * `name` is the name of an attribute or property (for example, href).\n * `type` indicates where the value is being inserted: one of property, attribute, or text.\n * `node` is the node where the value is being inserted.\n *\n * @type {(function(*,string,string,?Node):*)|undefined}\n */\nexport let sanitizeDOMValue =\n  window.Polymer && window.Polymer.sanitizeDOMValue || undefined;\n\n/**\n * Sets the global sanitizeDOMValue available via this module's exported\n * `sanitizeDOMValue` variable.\n *\n * @param {(function(*,string,string,?Node):*)|undefined} newSanitizeDOMValue the global sanitizeDOMValue callback\n * @return {void}\n */\nexport const setSanitizeDOMValue = function(newSanitizeDOMValue) {\n  sanitizeDOMValue = newSanitizeDOMValue;\n};\n\n/**\n * Gets sanitizeDOMValue, for environments that don't well support `export let`.\n *\n * @return {(function(*,string,string,?Node):*)|undefined} sanitizeDOMValue\n */\nexport const getSanitizeDOMValue = function() {\n  return sanitizeDOMValue;\n};\n\n/**\n * Globally settable property to make Polymer Gestures use passive TouchEvent listeners when recognizing gestures.\n * When set to `true`, gestures made from touch will not be able to prevent scrolling, allowing for smoother\n * scrolling performance.\n * Defaults to `false` for backwards compatibility.\n */\nexport let passiveTouchGestures =\n  window.Polymer && window.Polymer.setPassiveTouchGestures || false;\n\n/**\n * Sets `passiveTouchGestures` globally for all elements using Polymer Gestures.\n *\n * @param {boolean} usePassive enable or disable passive touch gestures globally\n * @return {void}\n */\nexport const setPassiveTouchGestures = function(usePassive) {\n  passiveTouchGestures = usePassive;\n};\n\n/**\n * Setting to ensure Polymer template evaluation only occurs based on tempates\n * defined in trusted script.  When true, `<dom-module>` re-registration is\n * disallowed, `<dom-bind>` is disabled, and `<dom-if>`/`<dom-repeat>`\n * templates will only evaluate in the context of a trusted element template.\n */\nexport let strictTemplatePolicy =\n  window.Polymer && window.Polymer.strictTemplatePolicy || false;\n\n/**\n * Sets `strictTemplatePolicy` globally for all elements\n *\n * @param {boolean} useStrictPolicy enable or disable strict template policy\n *   globally\n * @return {void}\n */\nexport const setStrictTemplatePolicy = function(useStrictPolicy) {\n  strictTemplatePolicy = useStrictPolicy;\n};\n\n/**\n * Setting to enable dom-module lookup from Polymer.Element.  By default,\n * templates must be defined in script using the `static get template()`\n * getter and the `html` tag function.  To enable legacy loading of templates\n * via dom-module, set this flag to true.\n */\nexport let allowTemplateFromDomModule =\n  window.Polymer && window.Polymer.allowTemplateFromDomModule || false;\n\n/**\n * Sets `lookupTemplateFromDomModule` globally for all elements\n *\n * @param {boolean} allowDomModule enable or disable template lookup\n *   globally\n * @return {void}\n */\nexport const setAllowTemplateFromDomModule = function(allowDomModule) {\n  allowTemplateFromDomModule = allowDomModule;\n};\n\n/**\n * Setting to skip processing style includes and re-writing urls in css styles.\n * Normally \"included\" styles are pulled into the element and all urls in styles\n * are re-written to be relative to the containing script url.\n * If no includes or relative urls are used in styles, these steps can be\n * skipped as an optimization.\n */\nexport let legacyOptimizations =\n  window.Polymer && window.Polymer.legacyOptimizations || false;\n\n/**\n * Sets `legacyOptimizations` globally for all elements to enable optimizations\n * when only legacy based elements are used.\n *\n * @param {boolean} useLegacyOptimizations enable or disable legacy optimizations\n * includes and url rewriting\n * @return {void}\n */\nexport const setLegacyOptimizations = function(useLegacyOptimizations) {\n  legacyOptimizations = useLegacyOptimizations;\n};\n\n/**\n * Setting to add warnings useful when migrating from Polymer 1.x to 2.x.\n */\nexport let legacyWarnings =\n  window.Polymer && window.Polymer.legacyWarnings || false;\n\n/**\n * Sets `legacyWarnings` globally for all elements to migration warnings.\n *\n * @param {boolean} useLegacyWarnings enable or disable warnings\n * @return {void}\n */\nexport const setLegacyWarnings = function(useLegacyWarnings) {\n  legacyWarnings = useLegacyWarnings;\n};\n\n/**\n * Setting to perform initial rendering synchronously when running under ShadyDOM.\n * This matches the behavior of Polymer 1.\n */\nexport let syncInitialRender =\n  window.Polymer && window.Polymer.syncInitialRender || false;\n\n/**\n * Sets `syncInitialRender` globally for all elements to enable synchronous\n * initial rendering.\n *\n * @param {boolean} useSyncInitialRender enable or disable synchronous initial\n * rendering globally.\n * @return {void}\n */\nexport const setSyncInitialRender = function(useSyncInitialRender) {\n  syncInitialRender = useSyncInitialRender;\n};\n\n/**\n * Setting to retain the legacy Polymer 1 behavior for multi-property\n * observers around undefined values. Observers and computed property methods\n * are not called until no argument is undefined.\n */\nexport let legacyUndefined =\n  window.Polymer && window.Polymer.legacyUndefined || false;\n\n/**\n * Sets `legacyUndefined` globally for all elements to enable legacy\n * multi-property behavior for undefined values.\n *\n * @param {boolean} useLegacyUndefined enable or disable legacy\n * multi-property behavior for undefined.\n * @return {void}\n */\nexport const setLegacyUndefined = function(useLegacyUndefined) {\n  legacyUndefined = useLegacyUndefined;\n};\n\n/**\n * Setting to ensure computed properties are computed in order to ensure\n * re-computation never occurs in a given turn.\n */\nexport let orderedComputed =\n  window.Polymer && window.Polymer.orderedComputed || false;\n\n/**\n * Sets `orderedComputed` globally for all elements to enable ordered computed\n * property computation.\n *\n * @param {boolean} useOrderedComputed enable or disable ordered computed effects\n * @return {void}\n */\nexport const setOrderedComputed = function(useOrderedComputed) {\n  orderedComputed = useOrderedComputed;\n};\n\n/**\n * Setting to cancel synthetic click events fired by older mobile browsers. Modern browsers\n * no longer fire synthetic click events, and the cancellation behavior can interfere\n * when programmatically clicking on elements.\n */\nexport let cancelSyntheticClickEvents = true;\n\n/**\n * Sets `setCancelSyntheticEvents` globally for all elements to cancel synthetic click events.\n *\n * @param {boolean} useCancelSyntheticClickEvents enable or disable cancelling synthetic\n * events\n * @return {void}\n */\nexport const setCancelSyntheticClickEvents = function(useCancelSyntheticClickEvents) {\n  cancelSyntheticClickEvents = useCancelSyntheticClickEvents;\n};\n\n/**\n * Setting to remove nested templates inside `dom-if` and `dom-repeat` as\n * part of element template parsing.  This is a performance optimization that\n * eliminates most of the tax of needing two elements due to the loss of\n * type-extended templates as a result of the V1 specification changes.\n */\nexport let removeNestedTemplates =\n  window.Polymer && window.Polymer.removeNestedTemplates || false;\n\n/**\n * Sets `removeNestedTemplates` globally, to eliminate nested templates\n * inside `dom-if` and `dom-repeat` as part of template parsing.\n *\n * @param {boolean} useRemoveNestedTemplates enable or disable removing nested\n *   templates during parsing\n * @return {void}\n */\nexport const setRemoveNestedTemplates = function(useRemoveNestedTemplates) {\n  removeNestedTemplates = useRemoveNestedTemplates;\n};\n\n/**\n * Setting to place `dom-if` elements in a performance-optimized mode that takes\n * advantage of lighter-weight host runtime template stamping to eliminate the\n * need for an intermediate Templatizer `TemplateInstance` to mange the nodes\n * stamped by `dom-if`.  Under this setting, any Templatizer-provided API's\n * such as `modelForElement` will not be available for nodes stamped by\n * `dom-if`.\n */\nexport let fastDomIf = window.Polymer && window.Polymer.fastDomIf || false;\n\n/**\n * Sets `fastDomIf` globally, to put `dom-if` in a performance-optimized mode.\n *\n * @param {boolean} useFastDomIf enable or disable `dom-if` fast-mode\n * @return {void}\n */\nexport const setFastDomIf = function(useFastDomIf) {\n  fastDomIf = useFastDomIf;\n};\n\n/**\n * Setting to disable `dom-change` and `rendered-item-count` events from\n * `dom-if` and `dom-repeat`. Users can opt back into `dom-change` events by\n * setting the `notify-dom-change` attribute (`notifyDomChange: true` property)\n * to `dom-if`/`don-repeat` instances.\n */\nexport let suppressTemplateNotifications =\n  window.Polymer && window.Polymer.suppressTemplateNotifications || false;\n\n/**\n * Sets `suppressTemplateNotifications` globally, to disable `dom-change` and\n * `rendered-item-count` events from `dom-if` and `dom-repeat`.\n *\n * @param {boolean} suppress enable or disable `suppressTemplateNotifications`\n * @return {void}\n */\nexport const setSuppressTemplateNotifications = function(suppress) {\n  suppressTemplateNotifications = suppress;\n};\n\n/**\n * Setting to disable use of dynamic attributes. This is an optimization\n * to avoid setting `observedAttributes`. Instead attributes are read\n * once at create time and set/removeAttribute are patched.\n */\nexport let legacyNoObservedAttributes =\n  window.Polymer && window.Polymer.legacyNoObservedAttributes || false;\n\n/**\n * Sets `legacyNoObservedAttributes` globally, to disable `observedAttributes`.\n *\n * @param {boolean} noObservedAttributes enable or disable `legacyNoObservedAttributes`\n * @return {void}\n */\nexport const setLegacyNoObservedAttributes = function(noObservedAttributes) {\n  legacyNoObservedAttributes = noObservedAttributes;\n};\n\n/**\n * Setting to enable use of `adoptedStyleSheets` for sharing style sheets\n * between component instances' shadow roots, if the app uses built Shady CSS\n * styles.\n */\nexport let useAdoptedStyleSheetsWithBuiltCSS =\n  window.Polymer && window.Polymer.useAdoptedStyleSheetsWithBuiltCSS || false;\n\n/**\n * Sets `useAdoptedStyleSheetsWithBuiltCSS` globally.\n *\n * @param {boolean} value enable or disable `useAdoptedStyleSheetsWithBuiltCSS`\n * @return {void}\n */\nexport const setUseAdoptedStyleSheetsWithBuiltCSS = function(value) {\n  useAdoptedStyleSheetsWithBuiltCSS = value;\n};\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\n\n// unique global id for deduping mixins.\nlet dedupeId = 0;\n\n/**\n * @constructor\n * @extends {Function}\n * @private\n */\nfunction MixinFunction(){}\n/** @type {(WeakMap | undefined)} */\nMixinFunction.prototype.__mixinApplications;\n/** @type {(Object | undefined)} */\nMixinFunction.prototype.__mixinSet;\n\n/* eslint-disable valid-jsdoc */\n/**\n * Wraps an ES6 class expression mixin such that the mixin is only applied\n * if it has not already been applied its base argument. Also memoizes mixin\n * applications.\n *\n * @template T\n * @param {T} mixin ES6 class expression mixin to wrap\n * @return {T}\n * @suppress {invalidCasts}\n */\nexport const dedupingMixin = function(mixin) {\n  let mixinApplications = /** @type {!MixinFunction} */(mixin).__mixinApplications;\n  if (!mixinApplications) {\n    mixinApplications = new WeakMap();\n    /** @type {!MixinFunction} */(mixin).__mixinApplications = mixinApplications;\n  }\n  // maintain a unique id for each mixin\n  let mixinDedupeId = dedupeId++;\n  function dedupingMixin(base) {\n    let baseSet = /** @type {!MixinFunction} */(base).__mixinSet;\n    if (baseSet && baseSet[mixinDedupeId]) {\n      return base;\n    }\n    let map = mixinApplications;\n    let extended = map.get(base);\n    if (!extended) {\n      extended = /** @type {!Function} */(mixin)(base);\n      map.set(base, extended);\n      // copy inherited mixin set from the extended class, or the base class\n      // NOTE: we avoid use of Set here because some browser (IE11)\n      // cannot extend a base Set via the constructor.\n      let mixinSet = Object.create(/** @type {!MixinFunction} */(extended).__mixinSet || baseSet || null);\n      mixinSet[mixinDedupeId] = true;\n      /** @type {!MixinFunction} */(extended).__mixinSet = mixinSet;\n    }\n    return extended;\n  }\n\n  return dedupingMixin;\n};\n/* eslint-enable valid-jsdoc */\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport '../utils/boot.js';\n\nimport { resolveUrl, pathFromUrl } from '../utils/resolve-url.js';\nimport { strictTemplatePolicy } from '../utils/settings.js';\n\nlet modules = {};\nlet lcModules = {};\n/**\n * Sets a dom-module into the global registry by id.\n *\n * @param {string} id dom-module id\n * @param {DomModule} module dom-module instance\n * @return {void}\n */\nfunction setModule(id, module) {\n  // store id separate from lowercased id so that\n  // in all cases mixedCase id will stored distinctly\n  // and lowercase version is a fallback\n  modules[id] = lcModules[id.toLowerCase()] = module;\n}\n/**\n * Retrieves a dom-module from the global registry by id.\n *\n * @param {string} id dom-module id\n * @return {DomModule!} dom-module instance\n */\nfunction findModule(id) {\n  return modules[id] || lcModules[id.toLowerCase()];\n}\n\nfunction styleOutsideTemplateCheck(inst) {\n  if (inst.querySelector('style')) {\n    console.warn('dom-module %s has style outside template', inst.id);\n  }\n}\n\n/**\n * The `dom-module` element registers the dom it contains to the name given\n * by the module's id attribute. It provides a unified database of dom\n * accessible via its static `import` API.\n *\n * A key use case of `dom-module` is for providing custom element `<template>`s\n * via HTML imports that are parsed by the native HTML parser, that can be\n * relocated during a bundling pass and still looked up by `id`.\n *\n * Example:\n *\n *     <dom-module id=\"foo\">\n *       <img src=\"stuff.png\">\n *     </dom-module>\n *\n * Then in code in some other location that cannot access the dom-module above\n *\n *     let img = customElements.get('dom-module').import('foo', 'img');\n *\n * @customElement\n * @extends HTMLElement\n * @summary Custom element that provides a registry of relocatable DOM content\n *   by `id` that is agnostic to bundling.\n * @unrestricted\n */\nexport class DomModule extends HTMLElement {\n\n  /** @override */\n  static get observedAttributes() { return ['id']; }\n\n  /**\n   * Retrieves the element specified by the css `selector` in the module\n   * registered by `id`. For example, this.import('foo', 'img');\n   * @param {string} id The id of the dom-module in which to search.\n   * @param {string=} selector The css selector by which to find the element.\n   * @return {Element} Returns the element which matches `selector` in the\n   * module registered at the specified `id`.\n   *\n   * @export\n   * @nocollapse Referred to indirectly in style-gather.js\n   */\n  static import(id, selector) {\n    if (id) {\n      let m = findModule(id);\n      if (m && selector) {\n        return m.querySelector(selector);\n      }\n      return m;\n    }\n    return null;\n  }\n\n  /* eslint-disable no-unused-vars */\n  /**\n   * @param {string} name Name of attribute.\n   * @param {?string} old Old value of attribute.\n   * @param {?string} value Current value of attribute.\n   * @param {?string} namespace Attribute namespace.\n   * @return {void}\n   * @override\n   */\n  attributeChangedCallback(name, old, value, namespace) {\n    if (old !== value) {\n      this.register();\n    }\n  }\n  /* eslint-enable no-unused-args */\n\n  /**\n   * The absolute URL of the original location of this `dom-module`.\n   *\n   * This value will differ from this element's `ownerDocument` in the\n   * following ways:\n   * - Takes into account any `assetpath` attribute added during bundling\n   *   to indicate the original location relative to the bundled location\n   * - Uses the HTMLImports polyfill's `importForElement` API to ensure\n   *   the path is relative to the import document's location since\n   *   `ownerDocument` is not currently polyfilled\n   */\n  get assetpath() {\n    // Don't override existing assetpath.\n    if (!this.__assetpath) {\n      // note: assetpath set via an attribute must be relative to this\n      // element's location; accommodate polyfilled HTMLImports\n      const owner = window.HTMLImports && HTMLImports.importForElement ?\n        HTMLImports.importForElement(this) || document : this.ownerDocument;\n      const url = resolveUrl(\n        this.getAttribute('assetpath') || '', owner.baseURI);\n      this.__assetpath = pathFromUrl(url);\n    }\n    return this.__assetpath;\n  }\n\n  /**\n   * Registers the dom-module at a given id. This method should only be called\n   * when a dom-module is imperatively created. For\n   * example, `document.createElement('dom-module').register('foo')`.\n   * @param {string=} id The id at which to register the dom-module.\n   * @return {void}\n   */\n  register(id) {\n    id = id || this.id;\n    if (id) {\n      // Under strictTemplatePolicy, reject and null out any re-registered\n      // dom-module since it is ambiguous whether first-in or last-in is trusted\n      if (strictTemplatePolicy && findModule(id) !== undefined) {\n        setModule(id, null);\n        throw new Error(`strictTemplatePolicy: dom-module ${id} re-registered`);\n      }\n      this.id = id;\n      setModule(id, this);\n      styleOutsideTemplateCheck(this);\n    }\n  }\n}\n\nDomModule.prototype['modules'] = modules;\n\ncustomElements.define('dom-module', DomModule);\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\n/**\n * Module with utilities for collection CSS text from `<templates>`, external\n * stylesheets, and `dom-module`s.\n *\n * @summary Module with utilities for collection CSS text from various sources.\n */\n\nimport { DomModule } from '../elements/dom-module.js';\nimport { resolveCss } from './resolve-url.js';\n\nconst MODULE_STYLE_LINK_SELECTOR = 'link[rel=import][type~=css]';\nconst INCLUDE_ATTR = 'include';\nconst SHADY_UNSCOPED_ATTR = 'shady-unscoped';\n\n/**\n * @param {string} moduleId .\n * @return {?DomModule} .\n */\nfunction importModule(moduleId) {\n  return /** @type {?DomModule} */(DomModule.import(moduleId));\n}\n\nfunction styleForImport(importDoc) {\n  // NOTE: polyfill affordance.\n  // under the HTMLImports polyfill, there will be no 'body',\n  // but the import pseudo-doc can be used directly.\n  let container = importDoc.body ? importDoc.body : importDoc;\n  const importCss = resolveCss(container.textContent,\n    importDoc.baseURI);\n  const style = document.createElement('style');\n  style.textContent = importCss;\n  return style;\n}\n\n/** @typedef {{assetpath: string}} */\nlet templateWithAssetPath; // eslint-disable-line no-unused-vars\n\n\n/**\n * Returns a list of <style> elements in a space-separated list of `dom-module`s.\n *\n * @function\n * @param {string} moduleIds List of dom-module id's within which to\n * search for css.\n * @return {!Array<!HTMLStyleElement>} Array of contained <style> elements\n */\nexport function stylesFromModules(moduleIds) {\n const modules = moduleIds.trim().split(/\\s+/);\n const styles = [];\n for (let i=0; i < modules.length; i++) {\n   styles.push(...stylesFromModule(modules[i]));\n }\n return styles;\n}\n\n/**\n * Returns a list of <style> elements in a given `dom-module`.\n * Styles in a `dom-module` can come either from `<style>`s within the\n * first `<template>`, or else from one or more\n * `<link rel=\"import\" type=\"css\">` links outside the template.\n *\n * @param {string} moduleId dom-module id to gather styles from\n * @return {!Array<!HTMLStyleElement>} Array of contained styles.\n */\nexport function stylesFromModule(moduleId) {\n  const m = importModule(moduleId);\n\n  if (!m) {\n    console.warn('Could not find style data in module named', moduleId);\n    return [];\n  }\n\n  if (m._styles === undefined) {\n    const styles = [];\n    // module imports: <link rel=\"import\" type=\"css\">\n    styles.push(..._stylesFromModuleImports(m));\n    // include css from the first template in the module\n    const template = /** @type {?HTMLTemplateElement} */(\n        m.querySelector('template'));\n    if (template) {\n      styles.push(...stylesFromTemplate(template,\n        /** @type {templateWithAssetPath} */(m).assetpath));\n    }\n\n    m._styles = styles;\n  }\n\n  return m._styles;\n}\n\n/**\n * Returns the `<style>` elements within a given template.\n *\n * @param {!HTMLTemplateElement} template Template to gather styles from\n * @param {string=} baseURI baseURI for style content\n * @return {!Array<!HTMLStyleElement>} Array of styles\n */\nexport function stylesFromTemplate(template, baseURI) {\n  if (!template._styles) {\n    const styles = [];\n    // if element is a template, get content from its .content\n    const e$ = template.content.querySelectorAll('style');\n    for (let i=0; i < e$.length; i++) {\n      let e = e$[i];\n      // support style sharing by allowing styles to \"include\"\n      // other dom-modules that contain styling\n      let include = e.getAttribute(INCLUDE_ATTR);\n      if (include) {\n        styles.push(...stylesFromModules(include).filter(function(item, index, self) {\n          return self.indexOf(item) === index;\n        }));\n      }\n      if (baseURI) {\n        e.textContent =\n            resolveCss(e.textContent, /** @type {string} */ (baseURI));\n      }\n      styles.push(e);\n    }\n    template._styles = styles;\n  }\n  return template._styles;\n}\n\n/**\n * Returns a list of <style> elements  from stylesheets loaded via `<link rel=\"import\" type=\"css\">` links within the specified `dom-module`.\n *\n * @param {string} moduleId Id of `dom-module` to gather CSS from\n * @return {!Array<!HTMLStyleElement>} Array of contained styles.\n */\nexport function stylesFromModuleImports(moduleId) {\n let m = importModule(moduleId);\n return m ? _stylesFromModuleImports(m) : [];\n}\n\n/**\n * @param {!HTMLElement} module dom-module element that could contain `<link rel=\"import\" type=\"css\">` styles\n * @return {!Array<!HTMLStyleElement>} Array of contained styles\n */\nfunction _stylesFromModuleImports(module) {\n  const styles = [];\n  const p$ = module.querySelectorAll(MODULE_STYLE_LINK_SELECTOR);\n  for (let i=0; i < p$.length; i++) {\n    let p = p$[i];\n    if (p.import) {\n      const importDoc = p.import;\n      const unscoped = p.hasAttribute(SHADY_UNSCOPED_ATTR);\n      if (unscoped && !importDoc._unscopedStyle) {\n        const style = styleForImport(importDoc);\n        style.setAttribute(SHADY_UNSCOPED_ATTR, '');\n        importDoc._unscopedStyle = style;\n      } else if (!importDoc._style) {\n        importDoc._style = styleForImport(importDoc);\n      }\n      styles.push(unscoped ? importDoc._unscopedStyle : importDoc._style);\n    }\n  }\n  return styles;\n}\n\n/**\n *\n * Returns CSS text of styles in a space-separated list of `dom-module`s.\n * Note: This method is deprecated, use `stylesFromModules` instead.\n *\n * @deprecated\n * @param {string} moduleIds List of dom-module id's within which to\n * search for css.\n * @return {string} Concatenated CSS content from specified `dom-module`s\n */\nexport function cssFromModules(moduleIds) {\n let modules = moduleIds.trim().split(/\\s+/);\n let cssText = '';\n for (let i=0; i < modules.length; i++) {\n   cssText += cssFromModule(modules[i]);\n }\n return cssText;\n}\n\n/**\n * Returns CSS text of styles in a given `dom-module`.  CSS in a `dom-module`\n * can come either from `<style>`s within the first `<template>`, or else\n * from one or more `<link rel=\"import\" type=\"css\">` links outside the\n * template.\n *\n * Any `<styles>` processed are removed from their original location.\n * Note: This method is deprecated, use `styleFromModule` instead.\n *\n * @deprecated\n * @param {string} moduleId dom-module id to gather styles from\n * @return {string} Concatenated CSS content from specified `dom-module`\n */\nexport function cssFromModule(moduleId) {\n  let m = importModule(moduleId);\n  if (m && m._cssText === undefined) {\n    // module imports: <link rel=\"import\" type=\"css\">\n    let cssText = _cssFromModuleImports(m);\n    // include css from the first template in the module\n    let t = /** @type {?HTMLTemplateElement} */(m.querySelector('template'));\n    if (t) {\n      cssText += cssFromTemplate(t,\n        /** @type {templateWithAssetPath} */(m).assetpath);\n    }\n    m._cssText = cssText || null;\n  }\n  if (!m) {\n    console.warn('Could not find style data in module named', moduleId);\n  }\n  return m && m._cssText || '';\n}\n\n/**\n * Returns CSS text of `<styles>` within a given template.\n *\n * Any `<styles>` processed are removed from their original location.\n * Note: This method is deprecated, use `styleFromTemplate` instead.\n *\n * @deprecated\n * @param {!HTMLTemplateElement} template Template to gather styles from\n * @param {string} baseURI Base URI to resolve the URL against\n * @return {string} Concatenated CSS content from specified template\n */\nexport function cssFromTemplate(template, baseURI) {\n  let cssText = '';\n  const e$ = stylesFromTemplate(template, baseURI);\n  // if element is a template, get content from its .content\n  for (let i=0; i < e$.length; i++) {\n    let e = e$[i];\n    if (e.parentNode) {\n      e.parentNode.removeChild(e);\n    }\n    cssText += e.textContent;\n  }\n  return cssText;\n}\n\n/**\n * Returns CSS text from stylesheets loaded via `<link rel=\"import\" type=\"css\">`\n * links within the specified `dom-module`.\n *\n * Note: This method is deprecated, use `stylesFromModuleImports` instead.\n *\n * @deprecated\n *\n * @param {string} moduleId Id of `dom-module` to gather CSS from\n * @return {string} Concatenated CSS content from links in specified `dom-module`\n */\nexport function cssFromModuleImports(moduleId) {\n  let m = importModule(moduleId);\n  return m ? _cssFromModuleImports(m) : '';\n}\n\n/**\n * @deprecated\n * @param {!HTMLElement} module dom-module element that could contain `<link rel=\"import\" type=\"css\">` styles\n * @return {string} Concatenated CSS content from links in the dom-module\n */\nfunction _cssFromModuleImports(module) {\n  let cssText = '';\n  let styles = _stylesFromModuleImports(module);\n  for (let i=0; i < styles.length; i++) {\n    cssText += styles[i].textContent;\n  }\n  return cssText;\n}\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\n/* eslint-disable valid-jsdoc */\n/**\n * Node wrapper to ensure ShadowDOM safe operation regardless of polyfill\n * presence or mode. Note that with the introduction of `ShadyDOM.noPatch`,\n * a node wrapper must be used to access ShadowDOM API.\n * This is similar to using `Polymer.dom` but relies exclusively\n * on the presence of the ShadyDOM polyfill rather than requiring the loading\n * of legacy (Polymer.dom) API.\n * @type {function(Node):Node}\n */\nexport const wrap = (window['ShadyDOM'] && window['ShadyDOM']['noPatch'] && window['ShadyDOM']['wrap']) ?\n  window['ShadyDOM']['wrap'] :\n  (window['ShadyDOM'] ? (n) => ShadyDOM['patch'](n) : (n) => n);\n\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\n\n/**\n * Module with utilities for manipulating structured data path strings.\n *\n * @summary Module with utilities for manipulating structured data path strings.\n */\n\n/**\n * Returns true if the given string is a structured data path (has dots).\n *\n * Example:\n *\n * ```\n * isPath('foo.bar.baz') // true\n * isPath('foo')         // false\n * ```\n *\n * @param {string} path Path string\n * @return {boolean} True if the string contained one or more dots\n */\nexport function isPath(path) {\n  return path.indexOf('.') >= 0;\n}\n\n/**\n * Returns the root property name for the given path.\n *\n * Example:\n *\n * ```\n * root('foo.bar.baz') // 'foo'\n * root('foo')         // 'foo'\n * ```\n *\n * @param {string} path Path string\n * @return {string} Root property name\n */\nexport function root(path) {\n  let dotIndex = path.indexOf('.');\n  if (dotIndex === -1) {\n    return path;\n  }\n  return path.slice(0, dotIndex);\n}\n\n/**\n * Given `base` is `foo.bar`, `foo` is an ancestor, `foo.bar` is not\n * Returns true if the given path is an ancestor of the base path.\n *\n * Example:\n *\n * ```\n * isAncestor('foo.bar', 'foo')         // true\n * isAncestor('foo.bar', 'foo.bar')     // false\n * isAncestor('foo.bar', 'foo.bar.baz') // false\n * ```\n *\n * @param {string} base Path string to test against.\n * @param {string} path Path string to test.\n * @return {boolean} True if `path` is an ancestor of `base`.\n */\nexport function isAncestor(base, path) {\n  //     base.startsWith(path + '.');\n  return base.indexOf(path + '.') === 0;\n}\n\n/**\n * Given `base` is `foo.bar`, `foo.bar.baz` is an descendant\n *\n * Example:\n *\n * ```\n * isDescendant('foo.bar', 'foo.bar.baz') // true\n * isDescendant('foo.bar', 'foo.bar')     // false\n * isDescendant('foo.bar', 'foo')         // false\n * ```\n *\n * @param {string} base Path string to test against.\n * @param {string} path Path string to test.\n * @return {boolean} True if `path` is a descendant of `base`.\n */\nexport function isDescendant(base, path) {\n  //     path.startsWith(base + '.');\n  return path.indexOf(base + '.') === 0;\n}\n\n/**\n * Replaces a previous base path with a new base path, preserving the\n * remainder of the path.\n *\n * User must ensure `path` has a prefix of `base`.\n *\n * Example:\n *\n * ```\n * translate('foo.bar', 'zot', 'foo.bar.baz') // 'zot.baz'\n * ```\n *\n * @param {string} base Current base string to remove\n * @param {string} newBase New base string to replace with\n * @param {string} path Path to translate\n * @return {string} Translated string\n */\nexport function translate(base, newBase, path) {\n  return newBase + path.slice(base.length);\n}\n\n/**\n * @param {string} base Path string to test against\n * @param {string} path Path string to test\n * @return {boolean} True if `path` is equal to `base`\n */\nexport function matches(base, path) {\n  return (base === path) ||\n         isAncestor(base, path) ||\n         isDescendant(base, path);\n}\n\n/**\n * Converts array-based paths to flattened path.  String-based paths\n * are returned as-is.\n *\n * Example:\n *\n * ```\n * normalize(['foo.bar', 0, 'baz'])  // 'foo.bar.0.baz'\n * normalize('foo.bar.0.baz')        // 'foo.bar.0.baz'\n * ```\n *\n * @param {string | !Array<string|number>} path Input path\n * @return {string} Flattened path\n */\nexport function normalize(path) {\n  if (Array.isArray(path)) {\n    let parts = [];\n    for (let i=0; i<path.length; i++) {\n      let args = path[i].toString().split('.');\n      for (let j=0; j<args.length; j++) {\n        parts.push(args[j]);\n      }\n    }\n    return parts.join('.');\n  } else {\n    return path;\n  }\n}\n\n/**\n * Splits a path into an array of property names. Accepts either arrays\n * of path parts or strings.\n *\n * Example:\n *\n * ```\n * split(['foo.bar', 0, 'baz'])  // ['foo', 'bar', '0', 'baz']\n * split('foo.bar.0.baz')        // ['foo', 'bar', '0', 'baz']\n * ```\n *\n * @param {string | !Array<string|number>} path Input path\n * @return {!Array<string>} Array of path parts\n * @suppress {checkTypes}\n */\nexport function split(path) {\n  if (Array.isArray(path)) {\n    return normalize(path).split('.');\n  }\n  return path.toString().split('.');\n}\n\n/**\n * Reads a value from a path.  If any sub-property in the path is `undefined`,\n * this method returns `undefined` (will never throw.\n *\n * @param {Object} root Object from which to dereference path from\n * @param {string | !Array<string|number>} path Path to read\n * @param {Object=} info If an object is provided to `info`, the normalized\n *  (flattened) path will be set to `info.path`.\n * @return {*} Value at path, or `undefined` if the path could not be\n *  fully dereferenced.\n */\nexport function get(root, path, info) {\n  let prop = root;\n  let parts = split(path);\n  // Loop over path parts[0..n-1] and dereference\n  for (let i=0; i<parts.length; i++) {\n    if (!prop) {\n      return;\n    }\n    let part = parts[i];\n    prop = prop[part];\n  }\n  if (info) {\n    info.path = parts.join('.');\n  }\n  return prop;\n}\n\n/**\n * Sets a value to a path.  If any sub-property in the path is `undefined`,\n * this method will no-op.\n *\n * @param {Object} root Object from which to dereference path from\n * @param {string | !Array<string|number>} path Path to set\n * @param {*} value Value to set to path\n * @return {string | undefined} The normalized version of the input path\n */\nexport function set(root, path, value) {\n  let prop = root;\n  let parts = split(path);\n  let last = parts[parts.length-1];\n  if (parts.length > 1) {\n    // Loop over path parts[0..n-2] and dereference\n    for (let i=0; i<parts.length-1; i++) {\n      let part = parts[i];\n      prop = prop[part];\n      if (!prop) {\n        return;\n      }\n    }\n    // Set value to object at end of path\n    prop[last] = value;\n  } else {\n    // Simple property set\n    prop[path] = value;\n  }\n  return parts.join('.');\n}\n\n/**\n * Returns true if the given string is a structured data path (has dots).\n *\n * This function is deprecated.  Use `isPath` instead.\n *\n * Example:\n *\n * ```\n * isDeep('foo.bar.baz') // true\n * isDeep('foo')         // false\n * ```\n *\n * @deprecated\n * @param {string} path Path string\n * @return {boolean} True if the string contained one or more dots\n */\nexport const isDeep = isPath;\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\n\nconst caseMap = {};\nconst DASH_TO_CAMEL = /-[a-z]/g;\nconst CAMEL_TO_DASH = /([A-Z])/g;\n\n/**\n * @fileoverview Module with utilities for converting between \"dash-case\" and\n * \"camelCase\" identifiers.\n */\n\n/**\n * Converts \"dash-case\" identifier (e.g. `foo-bar-baz`) to \"camelCase\"\n * (e.g. `fooBarBaz`).\n *\n * @param {string} dash Dash-case identifier\n * @return {string} Camel-case representation of the identifier\n */\nexport function dashToCamelCase(dash) {\n  return caseMap[dash] || (\n    caseMap[dash] = dash.indexOf('-') < 0 ? dash : dash.replace(DASH_TO_CAMEL,\n      (m) => m[1].toUpperCase()\n    )\n  );\n}\n\n/**\n * Converts \"camelCase\" identifier (e.g. `fooBarBaz`) to \"dash-case\"\n * (e.g. `foo-bar-baz`).\n *\n * @param {string} camel Camel-case identifier\n * @return {string} Dash-case representation of the identifier\n */\nexport function camelToDashCase(camel) {\n  return caseMap[camel] || (\n    caseMap[camel] = camel.replace(CAMEL_TO_DASH, '-$1').toLowerCase()\n  );\n}\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\n/**\n * @fileoverview\n *\n * This module provides a number of strategies for enqueuing asynchronous\n * tasks. Each sub-module provides a standard `run(fn)` interface that returns a\n * handle, and a `cancel(handle)` interface for canceling async tasks before\n * they run.\n *\n * @summary Module that provides a number of strategies for enqueuing\n * asynchronous tasks.\n */\n\nimport './boot.js';\n\n// Microtask implemented using Mutation Observer\nlet microtaskCurrHandle = 0;\nlet microtaskLastHandle = 0;\nlet microtaskCallbacks = [];\nlet microtaskNodeContent = 0;\nlet microtaskScheduled = false;\nlet microtaskNode = document.createTextNode('');\nnew window.MutationObserver(microtaskFlush).observe(microtaskNode, {characterData: true});\n\nfunction microtaskFlush() {\n  microtaskScheduled = false;\n  const len = microtaskCallbacks.length;\n  for (let i = 0; i < len; i++) {\n    let cb = microtaskCallbacks[i];\n    if (cb) {\n      try {\n        cb();\n      } catch (e) {\n        setTimeout(() => { throw e; });\n      }\n    }\n  }\n  microtaskCallbacks.splice(0, len);\n  microtaskLastHandle += len;\n}\n\n/**\n * Async interface wrapper around `setTimeout`.\n *\n * @namespace\n * @summary Async interface wrapper around `setTimeout`.\n */\nconst timeOut = {\n  /**\n   * Returns a sub-module with the async interface providing the provided\n   * delay.\n   *\n   * @memberof timeOut\n   * @param {number=} delay Time to wait before calling callbacks in ms\n   * @return {!AsyncInterface} An async timeout interface\n   */\n  after(delay) {\n    return {\n      run(fn) { return window.setTimeout(fn, delay); },\n      cancel(handle) {\n        window.clearTimeout(handle);\n      }\n    };\n  },\n  /**\n   * Enqueues a function called in the next task.\n   *\n   * @memberof timeOut\n   * @param {!Function} fn Callback to run\n   * @param {number=} delay Delay in milliseconds\n   * @return {number} Handle used for canceling task\n   */\n  run(fn, delay) {\n    return window.setTimeout(fn, delay);\n  },\n  /**\n   * Cancels a previously enqueued `timeOut` callback.\n   *\n   * @memberof timeOut\n   * @param {number} handle Handle returned from `run` of callback to cancel\n   * @return {void}\n   */\n  cancel(handle) {\n    window.clearTimeout(handle);\n  }\n};\nexport {timeOut};\n\n/**\n * Async interface wrapper around `requestAnimationFrame`.\n *\n * @namespace\n * @summary Async interface wrapper around `requestAnimationFrame`.\n */\nconst animationFrame = {\n  /**\n   * Enqueues a function called at `requestAnimationFrame` timing.\n   *\n   * @memberof animationFrame\n   * @param {function(number):void} fn Callback to run\n   * @return {number} Handle used for canceling task\n   */\n  run(fn) {\n    return window.requestAnimationFrame(fn);\n  },\n  /**\n   * Cancels a previously enqueued `animationFrame` callback.\n   *\n   * @memberof animationFrame\n   * @param {number} handle Handle returned from `run` of callback to cancel\n   * @return {void}\n   */\n  cancel(handle) {\n    window.cancelAnimationFrame(handle);\n  }\n};\nexport {animationFrame};\n\n/**\n * Async interface wrapper around `requestIdleCallback`.  Falls back to\n * `setTimeout` on browsers that do not support `requestIdleCallback`.\n *\n * @namespace\n * @summary Async interface wrapper around `requestIdleCallback`.\n */\nconst idlePeriod = {\n  /**\n   * Enqueues a function called at `requestIdleCallback` timing.\n   *\n   * @memberof idlePeriod\n   * @param {function(!IdleDeadline):void} fn Callback to run\n   * @return {number} Handle used for canceling task\n   */\n  run(fn) {\n    return window.requestIdleCallback ?\n      window.requestIdleCallback(fn) :\n      window.setTimeout(fn, 16);\n  },\n  /**\n   * Cancels a previously enqueued `idlePeriod` callback.\n   *\n   * @memberof idlePeriod\n   * @param {number} handle Handle returned from `run` of callback to cancel\n   * @return {void}\n   */\n  cancel(handle) {\n    window.cancelIdleCallback ?\n      window.cancelIdleCallback(handle) :\n      window.clearTimeout(handle);\n  }\n};\nexport {idlePeriod};\n\n/**\n * Async interface for enqueuing callbacks that run at microtask timing.\n *\n * Note that microtask timing is achieved via a single `MutationObserver`,\n * and thus callbacks enqueued with this API will all run in a single\n * batch, and not interleaved with other microtasks such as promises.\n * Promises are avoided as an implementation choice for the time being\n * due to Safari bugs that cause Promises to lack microtask guarantees.\n *\n * @namespace\n * @summary Async interface for enqueuing callbacks that run at microtask\n *   timing.\n */\nconst microTask = {\n\n  /**\n   * Enqueues a function called at microtask timing.\n   *\n   * @memberof microTask\n   * @param {!Function=} callback Callback to run\n   * @return {number} Handle used for canceling task\n   */\n  run(callback) {\n    if (!microtaskScheduled) {\n      microtaskScheduled = true;\n      microtaskNode.textContent = microtaskNodeContent++;\n    }\n    microtaskCallbacks.push(callback);\n    return microtaskCurrHandle++;\n  },\n\n  /**\n   * Cancels a previously enqueued `microTask` callback.\n   *\n   * @memberof microTask\n   * @param {number} handle Handle returned from `run` of callback to cancel\n   * @return {void}\n   */\n  cancel(handle) {\n    const idx = handle - microtaskLastHandle;\n    if (idx >= 0) {\n      if (!microtaskCallbacks[idx]) {\n        throw new Error('invalid async handle: ' + handle);\n      }\n      microtaskCallbacks[idx] = null;\n    }\n  }\n\n};\nexport {microTask};\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport '../utils/boot.js';\n\nimport { dedupingMixin } from '../utils/mixin.js';\nimport { microTask } from '../utils/async.js';\nimport { wrap } from '../utils/wrap.js';\n\n/** @const {!AsyncInterface} */\nconst microtask = microTask;\n\n/**\n * Element class mixin that provides basic meta-programming for creating one\n * or more property accessors (getter/setter pair) that enqueue an async\n * (batched) `_propertiesChanged` callback.\n *\n * For basic usage of this mixin, call `MyClass.createProperties(props)`\n * once at class definition time to create property accessors for properties\n * named in props, implement `_propertiesChanged` to react as desired to\n * property changes, and implement `static get observedAttributes()` and\n * include lowercase versions of any property names that should be set from\n * attributes. Last, call `this._enableProperties()` in the element's\n * `connectedCallback` to enable the accessors.\n *\n * @mixinFunction\n * @polymer\n * @summary Element class mixin for reacting to property changes from\n *   generated property accessors.\n * @template T\n * @param {function(new:T)} superClass Class to apply mixin to.\n * @return {function(new:T)} superClass with mixin applied.\n */\nexport const PropertiesChanged = dedupingMixin(\n    /**\n     * @template T\n     * @param {function(new:T)} superClass Class to apply mixin to.\n     * @return {function(new:T)} superClass with mixin applied.\n     */\n    (superClass) => {\n\n  /**\n   * @polymer\n   * @mixinClass\n   * @implements {Polymer_PropertiesChanged}\n   * @unrestricted\n   */\n  class PropertiesChanged extends superClass {\n\n    /**\n     * Creates property accessors for the given property names.\n     * @param {!Object} props Object whose keys are names of accessors.\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static createProperties(props) {\n      const proto = this.prototype;\n      for (let prop in props) {\n        // don't stomp an existing accessor\n        if (!(prop in proto)) {\n          proto._createPropertyAccessor(prop);\n        }\n      }\n    }\n\n    /**\n     * Returns an attribute name that corresponds to the given property.\n     * The attribute name is the lowercased property name. Override to\n     * customize this mapping.\n     * @param {string} property Property to convert\n     * @return {string} Attribute name corresponding to the given property.\n     *\n     * @protected\n     * @nocollapse\n     */\n    static attributeNameForProperty(property) {\n      return property.toLowerCase();\n    }\n\n    /**\n     * Override point to provide a type to which to deserialize a value to\n     * a given property.\n     * @param {string} name Name of property\n     *\n     * @protected\n     * @nocollapse\n     */\n    static typeForProperty(name) { } //eslint-disable-line no-unused-vars\n\n    /**\n     * Creates a setter/getter pair for the named property with its own\n     * local storage.  The getter returns the value in the local storage,\n     * and the setter calls `_setProperty`, which updates the local storage\n     * for the property and enqueues a `_propertiesChanged` callback.\n     *\n     * This method may be called on a prototype or an instance.  Calling\n     * this method may overwrite a property value that already exists on\n     * the prototype/instance by creating the accessor.\n     *\n     * @param {string} property Name of the property\n     * @param {boolean=} readOnly When true, no setter is created; the\n     *   protected `_setProperty` function must be used to set the property\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _createPropertyAccessor(property, readOnly) {\n      this._addPropertyToAttributeMap(property);\n      if (!this.hasOwnProperty(JSCompiler_renameProperty('__dataHasAccessor', this))) {\n        this.__dataHasAccessor = Object.assign({}, this.__dataHasAccessor);\n      }\n      if (!this.__dataHasAccessor[property]) {\n        this.__dataHasAccessor[property] = true;\n        this._definePropertyAccessor(property, readOnly);\n      }\n    }\n\n    /**\n     * Adds the given `property` to a map matching attribute names\n     * to property names, using `attributeNameForProperty`. This map is\n     * used when deserializing attribute values to properties.\n     *\n     * @param {string} property Name of the property\n     * @override\n     */\n    _addPropertyToAttributeMap(property) {\n      if (!this.hasOwnProperty(JSCompiler_renameProperty('__dataAttributes', this))) {\n        this.__dataAttributes = Object.assign({}, this.__dataAttributes);\n      }\n      // This check is technically not correct; it's an optimization that\n      // assumes that if a _property_ name is already in the map (note this is\n      // an attr->property map), the property mapped directly to the attribute\n      // and it has already been mapped.  This would fail if\n      // `attributeNameForProperty` were overridden such that this was not the\n      // case.\n      let attr = this.__dataAttributes[property];\n      if (!attr) {\n        attr = this.constructor.attributeNameForProperty(property);\n        this.__dataAttributes[attr] = property;\n      }\n      return attr;\n    }\n\n    /**\n     * Defines a property accessor for the given property.\n     * @param {string} property Name of the property\n     * @param {boolean=} readOnly When true, no setter is created\n     * @return {void}\n     * @override\n     */\n     _definePropertyAccessor(property, readOnly) {\n      Object.defineProperty(this, property, {\n        /* eslint-disable valid-jsdoc */\n        /** @this {PropertiesChanged} */\n        get() {\n          // Inline for perf instead of using `_getProperty`\n          return this.__data[property];\n        },\n        /** @this {PropertiesChanged} */\n        set: readOnly ? function () {} : function (value) {\n          // Inline for perf instead of using `_setProperty`\n          if (this._setPendingProperty(property, value, true)) {\n            this._invalidateProperties();\n          }\n        }\n        /* eslint-enable */\n      });\n    }\n\n    constructor() {\n      super();\n      /** @type {boolean} */\n      this.__dataEnabled = false;\n      this.__dataReady = false;\n      this.__dataInvalid = false;\n      this.__data = {};\n      this.__dataPending = null;\n      this.__dataOld = null;\n      this.__dataInstanceProps = null;\n      /** @type {number} */\n      // NOTE: used to track re-entrant calls to `_flushProperties`\n      this.__dataCounter = 0;\n      this.__serializing = false;\n      this._initializeProperties();\n    }\n\n    /**\n     * Lifecycle callback called when properties are enabled via\n     * `_enableProperties`.\n     *\n     * Users may override this function to implement behavior that is\n     * dependent on the element having its property data initialized, e.g.\n     * from defaults (initialized from `constructor`, `_initializeProperties`),\n     * `attributeChangedCallback`, or values propagated from host e.g. via\n     * bindings.  `super.ready()` must be called to ensure the data system\n     * becomes enabled.\n     *\n     * @return {void}\n     * @public\n     * @override\n     */\n    ready() {\n      this.__dataReady = true;\n      this._flushProperties();\n    }\n\n    /**\n     * Initializes the local storage for property accessors.\n     *\n     * Provided as an override point for performing any setup work prior\n     * to initializing the property accessor system.\n     *\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _initializeProperties() {\n      // Capture instance properties; these will be set into accessors\n      // during first flush. Don't set them here, since we want\n      // these to overwrite defaults/constructor assignments\n      for (let p in this.__dataHasAccessor) {\n        if (this.hasOwnProperty(p)) {\n          this.__dataInstanceProps = this.__dataInstanceProps || {};\n          this.__dataInstanceProps[p] = this[p];\n          delete this[p];\n        }\n      }\n    }\n\n    /**\n     * Called at ready time with bag of instance properties that overwrote\n     * accessors when the element upgraded.\n     *\n     * The default implementation sets these properties back into the\n     * setter at ready time.  This method is provided as an override\n     * point for customizing or providing more efficient initialization.\n     *\n     * @param {Object} props Bag of property values that were overwritten\n     *   when creating property accessors.\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _initializeInstanceProperties(props) {\n      Object.assign(this, props);\n    }\n\n    /**\n     * Updates the local storage for a property (via `_setPendingProperty`)\n     * and enqueues a `_proeprtiesChanged` callback.\n     *\n     * @param {string} property Name of the property\n     * @param {*} value Value to set\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _setProperty(property, value) {\n      if (this._setPendingProperty(property, value)) {\n        this._invalidateProperties();\n      }\n    }\n\n    /**\n     * Returns the value for the given property.\n     * @param {string} property Name of property\n     * @return {*} Value for the given property\n     * @protected\n     * @override\n     */\n    _getProperty(property) {\n      return this.__data[property];\n    }\n\n    /* eslint-disable no-unused-vars */\n    /**\n     * Updates the local storage for a property, records the previous value,\n     * and adds it to the set of \"pending changes\" that will be passed to the\n     * `_propertiesChanged` callback.  This method does not enqueue the\n     * `_propertiesChanged` callback.\n     *\n     * @param {string} property Name of the property\n     * @param {*} value Value to set\n     * @param {boolean=} ext Not used here; affordance for closure\n     * @return {boolean} Returns true if the property changed\n     * @protected\n     * @override\n     */\n    _setPendingProperty(property, value, ext) {\n      let old = this.__data[property];\n      let changed = this._shouldPropertyChange(property, value, old);\n      if (changed) {\n        if (!this.__dataPending) {\n          this.__dataPending = {};\n          this.__dataOld = {};\n        }\n        // Ensure old is captured from the last turn\n        if (this.__dataOld && !(property in this.__dataOld)) {\n          this.__dataOld[property] = old;\n        }\n        this.__data[property] = value;\n        this.__dataPending[property] = value;\n      }\n      return changed;\n    }\n    /* eslint-enable */\n\n    /**\n     * @param {string} property Name of the property\n     * @return {boolean} Returns true if the property is pending.\n     */\n    _isPropertyPending(property) {\n      return !!(this.__dataPending && this.__dataPending.hasOwnProperty(property));\n    }\n\n    /**\n     * Marks the properties as invalid, and enqueues an async\n     * `_propertiesChanged` callback.\n     *\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _invalidateProperties() {\n      if (!this.__dataInvalid && this.__dataReady) {\n        this.__dataInvalid = true;\n        microtask.run(() => {\n          if (this.__dataInvalid) {\n            this.__dataInvalid = false;\n            this._flushProperties();\n          }\n        });\n      }\n    }\n\n    /**\n     * Call to enable property accessor processing. Before this method is\n     * called accessor values will be set but side effects are\n     * queued. When called, any pending side effects occur immediately.\n     * For elements, generally `connectedCallback` is a normal spot to do so.\n     * It is safe to call this method multiple times as it only turns on\n     * property accessors once.\n     *\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _enableProperties() {\n      if (!this.__dataEnabled) {\n        this.__dataEnabled = true;\n        if (this.__dataInstanceProps) {\n          this._initializeInstanceProperties(this.__dataInstanceProps);\n          this.__dataInstanceProps = null;\n        }\n        this.ready();\n      }\n    }\n\n    /**\n     * Calls the `_propertiesChanged` callback with the current set of\n     * pending changes (and old values recorded when pending changes were\n     * set), and resets the pending set of changes. Generally, this method\n     * should not be called in user code.\n     *\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _flushProperties() {\n      this.__dataCounter++;\n      const props = this.__data;\n      const changedProps = this.__dataPending;\n      const old = this.__dataOld;\n      if (this._shouldPropertiesChange(props, changedProps, old)) {\n        this.__dataPending = null;\n        this.__dataOld = null;\n        this._propertiesChanged(props, changedProps, old);\n      }\n      this.__dataCounter--;\n    }\n\n    /**\n     * Called in `_flushProperties` to determine if `_propertiesChanged`\n     * should be called. The default implementation returns true if\n     * properties are pending. Override to customize when\n     * `_propertiesChanged` is called.\n     * @param {!Object} currentProps Bag of all current accessor values\n     * @param {?Object} changedProps Bag of properties changed since the last\n     *   call to `_propertiesChanged`\n     * @param {?Object} oldProps Bag of previous values for each property\n     *   in `changedProps`\n     * @return {boolean} true if changedProps is truthy\n     * @override\n     */\n    _shouldPropertiesChange(currentProps, changedProps, oldProps) { // eslint-disable-line no-unused-vars\n      return Boolean(changedProps);\n    }\n\n    /**\n     * Callback called when any properties with accessors created via\n     * `_createPropertyAccessor` have been set.\n     *\n     * @param {!Object} currentProps Bag of all current accessor values\n     * @param {?Object} changedProps Bag of properties changed since the last\n     *   call to `_propertiesChanged`\n     * @param {?Object} oldProps Bag of previous values for each property\n     *   in `changedProps`\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _propertiesChanged(currentProps, changedProps, oldProps) { // eslint-disable-line no-unused-vars\n    }\n\n    /**\n     * Method called to determine whether a property value should be\n     * considered as a change and cause the `_propertiesChanged` callback\n     * to be enqueued.\n     *\n     * The default implementation returns `true` if a strict equality\n     * check fails. The method always returns false for `NaN`.\n     *\n     * Override this method to e.g. provide stricter checking for\n     * Objects/Arrays when using immutable patterns.\n     *\n     * @param {string} property Property name\n     * @param {*} value New property value\n     * @param {*} old Previous property value\n     * @return {boolean} Whether the property should be considered a change\n     *   and enqueue a `_proeprtiesChanged` callback\n     * @protected\n     * @override\n     */\n    _shouldPropertyChange(property, value, old) {\n      return (\n        // Strict equality check\n        (old !== value &&\n          // This ensures (old==NaN, value==NaN) always returns false\n          (old === old || value === value))\n      );\n    }\n\n    /**\n     * Implements native Custom Elements `attributeChangedCallback` to\n     * set an attribute value to a property via `_attributeToProperty`.\n     *\n     * @param {string} name Name of attribute that changed\n     * @param {?string} old Old attribute value\n     * @param {?string} value New attribute value\n     * @param {?string} namespace Attribute namespace.\n     * @return {void}\n     * @suppress {missingProperties} Super may or may not implement the callback\n     * @override\n     */\n    attributeChangedCallback(name, old, value, namespace) {\n      if (old !== value) {\n        this._attributeToProperty(name, value);\n      }\n      if (super.attributeChangedCallback) {\n        super.attributeChangedCallback(name, old, value, namespace);\n      }\n    }\n\n    /**\n     * Deserializes an attribute to its associated property.\n     *\n     * This method calls the `_deserializeValue` method to convert the string to\n     * a typed value.\n     *\n     * @param {string} attribute Name of attribute to deserialize.\n     * @param {?string} value of the attribute.\n     * @param {*=} type type to deserialize to, defaults to the value\n     * returned from `typeForProperty`\n     * @return {void}\n     * @override\n     */\n    _attributeToProperty(attribute, value, type) {\n      if (!this.__serializing) {\n        const map = this.__dataAttributes;\n        const property = map && map[attribute] || attribute;\n        this[property] = this._deserializeValue(value, type ||\n          this.constructor.typeForProperty(property));\n      }\n    }\n\n    /**\n     * Serializes a property to its associated attribute.\n     *\n     * @suppress {invalidCasts} Closure can't figure out `this` is an element.\n     *\n     * @param {string} property Property name to reflect.\n     * @param {string=} attribute Attribute name to reflect to.\n     * @param {*=} value Property value to refect.\n     * @return {void}\n     * @override\n     */\n    _propertyToAttribute(property, attribute, value) {\n      this.__serializing = true;\n      value = (arguments.length < 3) ? this[property] : value;\n      this._valueToNodeAttribute(/** @type {!HTMLElement} */(this), value,\n        attribute || this.constructor.attributeNameForProperty(property));\n      this.__serializing = false;\n    }\n\n    /**\n     * Sets a typed value to an HTML attribute on a node.\n     *\n     * This method calls the `_serializeValue` method to convert the typed\n     * value to a string.  If the `_serializeValue` method returns `undefined`,\n     * the attribute will be removed (this is the default for boolean\n     * type `false`).\n     *\n     * @param {Element} node Element to set attribute to.\n     * @param {*} value Value to serialize.\n     * @param {string} attribute Attribute name to serialize to.\n     * @return {void}\n     * @override\n     */\n    _valueToNodeAttribute(node, value, attribute) {\n      const str = this._serializeValue(value);\n      if (attribute === 'class' || attribute === 'name' || attribute === 'slot') {\n        node = /** @type {?Element} */(wrap(node));\n      }\n      if (str === undefined) {\n        node.removeAttribute(attribute);\n      } else {\n        node.setAttribute(\n            attribute,\n            // Closure's type for `setAttribute`'s second parameter incorrectly\n            // excludes `TrustedScript`.\n            (str === '' && window.trustedTypes) ?\n                /** @type {?} */ (window.trustedTypes.emptyScript) :\n                str);\n      }\n    }\n\n    /**\n     * Converts a typed JavaScript value to a string.\n     *\n     * This method is called when setting JS property values to\n     * HTML attributes.  Users may override this method to provide\n     * serialization for custom types.\n     *\n     * @param {*} value Property value to serialize.\n     * @return {string | undefined} String serialized from the provided\n     * property  value.\n     * @override\n     */\n    _serializeValue(value) {\n      switch (typeof value) {\n        case 'boolean':\n          return value ? '' : undefined;\n        default:\n          return value != null ? value.toString() : undefined;\n      }\n    }\n\n    /**\n     * Converts a string to a typed JavaScript value.\n     *\n     * This method is called when reading HTML attribute values to\n     * JS properties.  Users may override this method to provide\n     * deserialization for custom `type`s. Types for `Boolean`, `String`,\n     * and `Number` convert attributes to the expected types.\n     *\n     * @param {?string} value Value to deserialize.\n     * @param {*=} type Type to deserialize the string to.\n     * @return {*} Typed value deserialized from the provided string.\n     * @override\n     */\n    _deserializeValue(value, type) {\n      switch (type) {\n        case Boolean:\n          return (value !== null);\n        case Number:\n          return Number(value);\n        default:\n          return value;\n      }\n    }\n\n  }\n\n  return PropertiesChanged;\n});\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport '../utils/boot.js';\n\nimport { dedupingMixin } from '../utils/mixin.js';\nimport { camelToDashCase, dashToCamelCase } from '../utils/case-map.js';\nimport { PropertiesChanged } from './properties-changed.js';\n\n// Save map of native properties; this forms a blacklist or properties\n// that won't have their values \"saved\" by `saveAccessorValue`, since\n// reading from an HTMLElement accessor from the context of a prototype throws\nconst nativeProperties = {};\nlet proto = HTMLElement.prototype;\nwhile (proto) {\n  let props = Object.getOwnPropertyNames(proto);\n  for (let i=0; i<props.length; i++) {\n    nativeProperties[props[i]] = true;\n  }\n  proto = Object.getPrototypeOf(proto);\n}\n\nconst isTrustedType = (() => {\n  if (!window.trustedTypes) {\n    return () => false;\n  }\n  return (val) => trustedTypes.isHTML(val) ||\n        trustedTypes.isScript(val) || trustedTypes.isScriptURL(val);\n})();\n\n/**\n * Used to save the value of a property that will be overridden with\n * an accessor. If the `model` is a prototype, the values will be saved\n * in `__dataProto`, and it's up to the user (or downstream mixin) to\n * decide how/when to set these values back into the accessors.\n * If `model` is already an instance (it has a `__data` property), then\n * the value will be set as a pending property, meaning the user should\n * call `_invalidateProperties` or `_flushProperties` to take effect\n *\n * @param {Object} model Prototype or instance\n * @param {string} property Name of property\n * @return {void}\n * @private\n */\nfunction saveAccessorValue(model, property) {\n  // Don't read/store value for any native properties since they could throw\n  if (!nativeProperties[property]) {\n    let value = model[property];\n    if (value !== undefined) {\n      if (model.__data) {\n        // Adding accessor to instance; update the property\n        // It is the user's responsibility to call _flushProperties\n        model._setPendingProperty(property, value);\n      } else {\n        // Adding accessor to proto; save proto's value for instance-time use\n        if (!model.__dataProto) {\n          model.__dataProto = {};\n        } else if (!model.hasOwnProperty(JSCompiler_renameProperty('__dataProto', model))) {\n          model.__dataProto = Object.create(model.__dataProto);\n        }\n        model.__dataProto[property] = value;\n      }\n    }\n  }\n}\n\n/**\n * Element class mixin that provides basic meta-programming for creating one\n * or more property accessors (getter/setter pair) that enqueue an async\n * (batched) `_propertiesChanged` callback.\n *\n * For basic usage of this mixin:\n *\n * -   Declare attributes to observe via the standard `static get\n *     observedAttributes()`. Use `dash-case` attribute names to represent\n *     `camelCase` property names.\n * -   Implement the `_propertiesChanged` callback on the class.\n * -   Call `MyClass.createPropertiesForAttributes()` **once** on the class to\n *     generate property accessors for each observed attribute. This must be\n *     called before the first instance is created, for example, by calling it\n *     before calling `customElements.define`. It can also be called lazily from\n *     the element's `constructor`, as long as it's guarded so that the call is\n *     only made once, when the first instance is created.\n * -   Call `this._enableProperties()` in the element's `connectedCallback` to\n *     enable the accessors.\n *\n * Any `observedAttributes` will automatically be\n * deserialized via `attributeChangedCallback` and set to the associated\n * property using `dash-case`-to-`camelCase` convention.\n *\n * @mixinFunction\n * @polymer\n * @appliesMixin PropertiesChanged\n * @summary Element class mixin for reacting to property changes from\n *   generated property accessors.\n * @template T\n * @param {function(new:T)} superClass Class to apply mixin to.\n * @return {function(new:T)} superClass with mixin applied.\n */\nexport const PropertyAccessors = dedupingMixin(superClass => {\n\n  /**\n   * @constructor\n   * @implements {Polymer_PropertiesChanged}\n   * @unrestricted\n   * @private\n   */\n   const base = PropertiesChanged(superClass);\n\n  /**\n   * @polymer\n   * @mixinClass\n   * @implements {Polymer_PropertyAccessors}\n   * @extends {base}\n   * @unrestricted\n   */\n  class PropertyAccessors extends base {\n\n    /**\n     * Generates property accessors for all attributes in the standard\n     * static `observedAttributes` array.\n     *\n     * Attribute names are mapped to property names using the `dash-case` to\n     * `camelCase` convention\n     *\n     * @return {void}\n     * @nocollapse\n     */\n    static createPropertiesForAttributes() {\n      let a$ =  /** @type {?} */ (this).observedAttributes;\n      for (let i=0; i < a$.length; i++) {\n        this.prototype._createPropertyAccessor(dashToCamelCase(a$[i]));\n      }\n    }\n\n    /**\n     * Returns an attribute name that corresponds to the given property.\n     * By default, converts camel to dash case, e.g. `fooBar` to `foo-bar`.\n     * @param {string} property Property to convert\n     * @return {string} Attribute name corresponding to the given property.\n     *\n     * @protected\n     * @nocollapse\n     */\n    static attributeNameForProperty(property) {\n      return camelToDashCase(property);\n    }\n\n    /**\n     * Overrides PropertiesChanged implementation to initialize values for\n     * accessors created for values that already existed on the element\n     * prototype.\n     *\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _initializeProperties() {\n      if (this.__dataProto) {\n        this._initializeProtoProperties(this.__dataProto);\n        this.__dataProto = null;\n      }\n      super._initializeProperties();\n    }\n\n    /**\n     * Called at instance time with bag of properties that were overwritten\n     * by accessors on the prototype when accessors were created.\n     *\n     * The default implementation sets these properties back into the\n     * setter at instance time.  This method is provided as an override\n     * point for customizing or providing more efficient initialization.\n     *\n     * @param {Object} props Bag of property values that were overwritten\n     *   when creating property accessors.\n     * @return {void}\n     * @protected\n     * @override\n     */\n    _initializeProtoProperties(props) {\n      for (let p in props) {\n        this._setProperty(p, props[p]);\n      }\n    }\n\n    /**\n     * Ensures the element has the given attribute. If it does not,\n     * assigns the given value to the attribute.\n     *\n     * @suppress {invalidCasts} Closure can't figure out `this` is infact an\n     *     element\n     *\n     * @param {string} attribute Name of attribute to ensure is set.\n     * @param {string} value of the attribute.\n     * @return {void}\n     * @override\n     */\n    _ensureAttribute(attribute, value) {\n      const el = /** @type {!HTMLElement} */(this);\n      if (!el.hasAttribute(attribute)) {\n        this._valueToNodeAttribute(el, value, attribute);\n      }\n    }\n\n    /**\n     * Overrides PropertiesChanged implemention to serialize objects as JSON.\n     *\n     * @param {*} value Property value to serialize.\n     * @return {string | undefined} String serialized from the provided property\n     *     value.\n     * @override\n     */\n    _serializeValue(value) {\n      /* eslint-disable no-fallthrough */\n      switch (typeof value) {\n        case 'object':\n          if (value instanceof Date) {\n            return value.toString();\n          } else if (value) {\n            if (isTrustedType(value)) {\n              /**\n               * Here `value` isn't actually a string, but it should be\n               * passed into APIs that normally expect a string, like\n               * elem.setAttribute.\n               */\n              return /** @type {?} */ (value);\n            }\n            try {\n              return JSON.stringify(value);\n            } catch(x) {\n              return '';\n            }\n          }\n\n        default:\n          return super._serializeValue(value);\n      }\n    }\n\n    /**\n     * Converts a string to a typed JavaScript value.\n     *\n     * This method is called by Polymer when reading HTML attribute values to\n     * JS properties.  Users may override this method on Polymer element\n     * prototypes to provide deserialization for custom `type`s.  Note,\n     * the `type` argument is the value of the `type` field provided in the\n     * `properties` configuration object for a given property, and is\n     * by convention the constructor for the type to deserialize.\n     *\n     *\n     * @param {?string} value Attribute value to deserialize.\n     * @param {*=} type Type to deserialize the string to.\n     * @return {*} Typed value deserialized from the provided string.\n     * @override\n     */\n    _deserializeValue(value, type) {\n      /**\n       * @type {*}\n       */\n      let outValue;\n      switch (type) {\n        case Object:\n          try {\n            outValue = JSON.parse(/** @type {string} */(value));\n          } catch(x) {\n            // allow non-JSON literals like Strings and Numbers\n            outValue = value;\n          }\n          break;\n        case Array:\n          try {\n            outValue = JSON.parse(/** @type {string} */(value));\n          } catch(x) {\n            outValue = null;\n            console.warn(`Polymer::Attributes: couldn't decode Array as JSON: ${value}`);\n          }\n          break;\n        case Date:\n          outValue = isNaN(value) ? String(value) : Number(value);\n          outValue = new Date(outValue);\n          break;\n        default:\n          outValue = super._deserializeValue(value, type);\n          break;\n      }\n      return outValue;\n    }\n    /* eslint-enable no-fallthrough */\n\n    /**\n     * Overrides PropertiesChanged implementation to save existing prototype\n     * property value so that it can be reset.\n     * @param {string} property Name of the property\n     * @param {boolean=} readOnly When true, no setter is created\n     *\n     * When calling on a prototype, any overwritten values are saved in\n     * `__dataProto`, and it is up to the subclasser to decide how/when\n     * to set those properties back into the accessor.  When calling on an\n     * instance, the overwritten value is set via `_setPendingProperty`,\n     * and the user should call `_invalidateProperties` or `_flushProperties`\n     * for the values to take effect.\n     * @protected\n     * @return {void}\n     * @override\n     */\n    _definePropertyAccessor(property, readOnly) {\n      saveAccessorValue(this, property);\n      super._definePropertyAccessor(property, readOnly);\n    }\n\n    /**\n     * Returns true if this library created an accessor for the given property.\n     *\n     * @param {string} property Property name\n     * @return {boolean} True if an accessor was created\n     * @override\n     */\n    _hasAccessor(property) {\n      return this.__dataHasAccessor && this.__dataHasAccessor[property];\n    }\n\n    /**\n     * Returns true if the specified property has a pending change.\n     *\n     * @param {string} prop Property name\n     * @return {boolean} True if property has a pending change\n     * @protected\n     * @override\n     */\n    _isPropertyPending(prop) {\n      return Boolean(this.__dataPending && (prop in this.__dataPending));\n    }\n\n  }\n\n  return PropertyAccessors;\n\n});\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport '../utils/boot.js';\n\nimport { dedupingMixin } from '../utils/mixin.js';\n\n// 1.x backwards-compatible auto-wrapper for template type extensions\n// This is a clear layering violation and gives favored-nation status to\n// dom-if and dom-repeat templates.  This is a conceit we're choosing to keep\n// a.) to ease 1.x backwards-compatibility due to loss of `is`, and\n// b.) to maintain if/repeat capability in parser-constrained elements\n//     (e.g. table, select) in lieu of native CE type extensions without\n//     massive new invention in this space (e.g. directive system)\nconst templateExtensions = {\n  'dom-if': true,\n  'dom-repeat': true\n};\n\nlet placeholderBugDetect = false;\nlet placeholderBug = false;\n\nfunction hasPlaceholderBug() {\n  if (!placeholderBugDetect) {\n    placeholderBugDetect = true;\n    const t = document.createElement('textarea');\n    t.placeholder = 'a';\n    placeholderBug = t.placeholder === t.textContent;\n  }\n  return placeholderBug;\n}\n\n/**\n * Some browsers have a bug with textarea, where placeholder text is copied as\n * a textnode child of the textarea.\n *\n * If the placeholder is a binding, this can break template stamping in two\n * ways.\n *\n * One issue is that when the `placeholder` attribute is removed when the\n * binding is processed, the textnode child of the textarea is deleted, and the\n * template info tries to bind into that node.\n *\n * With `legacyOptimizations` in use, when the template is stamped and the\n * `textarea.textContent` binding is processed, no corresponding node is found\n * because it was removed during parsing. An exception is generated when this\n * binding is updated.\n *\n * With `legacyOptimizations` not in use, the template is cloned before\n * processing and this changes the above behavior. The cloned template also has\n * a value property set to the placeholder and textContent. This prevents the\n * removal of the textContent when the placeholder attribute is removed.\n * Therefore the exception does not occur. However, there is an extra\n * unnecessary binding.\n *\n * @param {!Node} node Check node for placeholder bug\n * @return {void}\n */\nfunction fixPlaceholder(node) {\n  if (hasPlaceholderBug() && node.localName === 'textarea' && node.placeholder\n        && node.placeholder === node.textContent) {\n    node.textContent = null;\n  }\n}\n\n/**\n * Copies an attribute from one element to another, converting the value to a\n * `TrustedScript` if it is named like a Polymer template event listener.\n *\n * @param {!Element} dest The element to set the attribute on\n * @param {!Element} src The element to read the attribute from\n * @param {string} name The name of the attribute\n */\nconst copyAttributeWithTemplateEventPolicy = (() => {\n  /**\n   * This `TrustedTypePolicy` is used to work around a Chrome bug in the Trusted\n   * Types API where any attribute that starts with `on` may only be set to a\n   * `TrustedScript` value, even if that attribute would not cause an event\n   * listener to be created. (See https://crbug.com/993268 for details.)\n   *\n   * Polymer's template system allows `<dom-if>` and `<dom-repeat>` to be\n   * written using the `<template is=\"...\">` syntax, even if there is no UA\n   * support for custom element extensions of built-in elements. In doing so, it\n   * copies attributes from the original `<template>` to a newly created\n   * `<dom-if>` or `<dom-repeat>`, which can trigger the bug mentioned above if\n   * any of those attributes uses Polymer's `on-` syntax for event listeners.\n   * (Note, the value of these `on-` listeners is not evaluated as script: it is\n   * the name of a member function of a component that will be used as the event\n   * listener.)\n   *\n   * @type {!TrustedTypePolicy|undefined}\n   */\n  const polymerTemplateEventAttributePolicy = window.trustedTypes &&\n      window.trustedTypes.createPolicy(\n          'polymer-template-event-attribute-policy', {\n            createScript: x => x,\n          });\n\n  return (dest, src, name) => {\n    const value = src.getAttribute(name);\n\n    if (polymerTemplateEventAttributePolicy && name.startsWith('on-')) {\n      dest.setAttribute(\n          name, polymerTemplateEventAttributePolicy.createScript(value, name));\n      return;\n    }\n\n    dest.setAttribute(name, value);\n  };\n})();\n\nfunction wrapTemplateExtension(node) {\n  let is = node.getAttribute('is');\n  if (is && templateExtensions[is]) {\n    let t = node;\n    t.removeAttribute('is');\n    node = t.ownerDocument.createElement(is);\n    t.parentNode.replaceChild(node, t);\n    node.appendChild(t);\n    while(t.attributes.length) {\n      const {name} = t.attributes[0];\n      copyAttributeWithTemplateEventPolicy(node, t, name);\n      t.removeAttribute(name);\n    }\n  }\n  return node;\n}\n\nfunction findTemplateNode(root, nodeInfo) {\n  // recursively ascend tree until we hit root\n  let parent = nodeInfo.parentInfo && findTemplateNode(root, nodeInfo.parentInfo);\n  // unwind the stack, returning the indexed node at each level\n  if (parent) {\n    // note: marginally faster than indexing via childNodes\n    // (http://jsperf.com/childnodes-lookup)\n    for (let n=parent.firstChild, i=0; n; n=n.nextSibling) {\n      if (nodeInfo.parentIndex === i++) {\n        return n;\n      }\n    }\n  } else {\n    return root;\n  }\n}\n\n// construct `$` map (from id annotations)\nfunction applyIdToMap(inst, map, node, nodeInfo) {\n  if (nodeInfo.id) {\n    map[nodeInfo.id] = node;\n  }\n}\n\n// install event listeners (from event annotations)\nfunction applyEventListener(inst, node, nodeInfo) {\n  if (nodeInfo.events && nodeInfo.events.length) {\n    for (let j=0, e$=nodeInfo.events, e; (j<e$.length) && (e=e$[j]); j++) {\n      inst._addMethodEventListenerToNode(node, e.name, e.value, inst);\n    }\n  }\n}\n\n// push configuration references at configure time\nfunction applyTemplateInfo(inst, node, nodeInfo, parentTemplateInfo) {\n  if (nodeInfo.templateInfo) {\n    // Give the node an instance of this templateInfo and set its parent\n    node._templateInfo = nodeInfo.templateInfo;\n    node._parentTemplateInfo = parentTemplateInfo;\n  }\n}\n\nfunction createNodeEventHandler(context, eventName, methodName) {\n  // Instances can optionally have a _methodHost which allows redirecting where\n  // to find methods. Currently used by `templatize`.\n  context = context._methodHost || context;\n  let handler = function(e) {\n    if (context[methodName]) {\n      context[methodName](e, e.detail);\n    } else {\n      console.warn('listener method `' + methodName + '` not defined');\n    }\n  };\n  return handler;\n}\n\n/**\n * Element mixin that provides basic template parsing and stamping, including\n * the following template-related features for stamped templates:\n *\n * - Declarative event listeners (`on-eventname=\"listener\"`)\n * - Map of node id's to stamped node instances (`this.$.id`)\n * - Nested template content caching/removal and re-installation (performance\n *   optimization)\n *\n * @mixinFunction\n * @polymer\n * @summary Element class mixin that provides basic template parsing and stamping\n */\nexport const TemplateStamp = dedupingMixin(\n    /**\n     * @template T\n     * @param {function(new:T)} superClass Class to apply mixin to.\n     * @return {function(new:T)} superClass with mixin applied.\n     */\n    (superClass) => {\n\n  /**\n   * @polymer\n   * @mixinClass\n   * @implements {Polymer_TemplateStamp}\n   */\n  class TemplateStamp extends superClass {\n\n    /**\n     * Scans a template to produce template metadata.\n     *\n     * Template-specific metadata are stored in the object returned, and node-\n     * specific metadata are stored in objects in its flattened `nodeInfoList`\n     * array.  Only nodes in the template that were parsed as nodes of\n     * interest contain an object in `nodeInfoList`.  Each `nodeInfo` object\n     * contains an `index` (`childNodes` index in parent) and optionally\n     * `parent`, which points to node info of its parent (including its index).\n     *\n     * The template metadata object returned from this method has the following\n     * structure (many fields optional):\n     *\n     * ```js\n     *   {\n     *     // Flattened list of node metadata (for nodes that generated metadata)\n     *     nodeInfoList: [\n     *       {\n     *         // `id` attribute for any nodes with id's for generating `$` map\n     *         id: {string},\n     *         // `on-event=\"handler\"` metadata\n     *         events: [\n     *           {\n     *             name: {string},   // event name\n     *             value: {string},  // handler method name\n     *           }, ...\n     *         ],\n     *         // Notes when the template contained a `<slot>` for shady DOM\n     *         // optimization purposes\n     *         hasInsertionPoint: {boolean},\n     *         // For nested `<template>`` nodes, nested template metadata\n     *         templateInfo: {object}, // nested template metadata\n     *         // Metadata to allow efficient retrieval of instanced node\n     *         // corresponding to this metadata\n     *         parentInfo: {number},   // reference to parent nodeInfo>\n     *         parentIndex: {number},  // index in parent's `childNodes` collection\n     *         infoIndex: {number},    // index of this `nodeInfo` in `templateInfo.nodeInfoList`\n     *       },\n     *       ...\n     *     ],\n     *     // When true, the template had the `strip-whitespace` attribute\n     *     // or was nested in a template with that setting\n     *     stripWhitespace: {boolean},\n     *     // For nested templates, nested template content is moved into\n     *     // a document fragment stored here; this is an optimization to\n     *     // avoid the cost of nested template cloning\n     *     content: {DocumentFragment}\n     *   }\n     * ```\n     *\n     * This method kicks off a recursive treewalk as follows:\n     *\n     * ```\n     *    _parseTemplate <---------------------+\n     *      _parseTemplateContent              |\n     *        _parseTemplateNode  <------------|--+\n     *          _parseTemplateNestedTemplate --+  |\n     *          _parseTemplateChildNodes ---------+\n     *          _parseTemplateNodeAttributes\n     *            _parseTemplateNodeAttribute\n     *\n     * ```\n     *\n     * These methods may be overridden to add custom metadata about templates\n     * to either `templateInfo` or `nodeInfo`.\n     *\n     * Note that this method may be destructive to the template, in that\n     * e.g. event annotations may be removed after being noted in the\n     * template metadata.\n     *\n     * @param {!HTMLTemplateElement} template Template to parse\n     * @param {TemplateInfo=} outerTemplateInfo Template metadata from the outer\n     *   template, for parsing nested templates\n     * @return {!TemplateInfo} Parsed template metadata\n     * @nocollapse\n     */\n    static _parseTemplate(template, outerTemplateInfo) {\n      // since a template may be re-used, memo-ize metadata\n      if (!template._templateInfo) {\n        // TODO(rictic): fix typing\n        let /** ? */ templateInfo = template._templateInfo = {};\n        templateInfo.nodeInfoList = [];\n        templateInfo.nestedTemplate = Boolean(outerTemplateInfo);\n        templateInfo.stripWhiteSpace =\n          (outerTemplateInfo && outerTemplateInfo.stripWhiteSpace) ||\n          (template.hasAttribute && template.hasAttribute('strip-whitespace'));\n         // TODO(rictic): fix typing\n         this._parseTemplateContent(\n             template, templateInfo, /** @type {?} */ ({parent: null}));\n      }\n      return template._templateInfo;\n    }\n\n    /**\n     * See docs for _parseTemplateNode.\n     *\n     * @param {!HTMLTemplateElement} template .\n     * @param {!TemplateInfo} templateInfo .\n     * @param {!NodeInfo} nodeInfo .\n     * @return {boolean} .\n     * @nocollapse\n     */\n    static _parseTemplateContent(template, templateInfo, nodeInfo) {\n      return this._parseTemplateNode(template.content, templateInfo, nodeInfo);\n    }\n\n    /**\n     * Parses template node and adds template and node metadata based on\n     * the current node, and its `childNodes` and `attributes`.\n     *\n     * This method may be overridden to add custom node or template specific\n     * metadata based on this node.\n     *\n     * @param {Node} node Node to parse\n     * @param {!TemplateInfo} templateInfo Template metadata for current template\n     * @param {!NodeInfo} nodeInfo Node metadata for current template.\n     * @return {boolean} `true` if the visited node added node-specific\n     *   metadata to `nodeInfo`\n     * @nocollapse\n     */\n    static _parseTemplateNode(node, templateInfo, nodeInfo) {\n      let noted = false;\n      let element = /** @type {!HTMLTemplateElement} */ (node);\n      if (element.localName == 'template' && !element.hasAttribute('preserve-content')) {\n        noted = this._parseTemplateNestedTemplate(element, templateInfo, nodeInfo) || noted;\n      } else if (element.localName === 'slot') {\n        // For ShadyDom optimization, indicating there is an insertion point\n        templateInfo.hasInsertionPoint = true;\n      }\n      fixPlaceholder(element);\n      if (element.firstChild) {\n        this._parseTemplateChildNodes(element, templateInfo, nodeInfo);\n      }\n      if (element.hasAttributes && element.hasAttributes()) {\n        noted = this._parseTemplateNodeAttributes(element, templateInfo, nodeInfo) || noted;\n      }\n      // Checking `nodeInfo.noted` allows a child node of this node (who gets\n      // access to `parentInfo`) to cause the parent to be noted, which\n      // otherwise has no return path via `_parseTemplateChildNodes` (used by\n      // some optimizations)\n      return noted || nodeInfo.noted;\n    }\n\n    /**\n     * Parses template child nodes for the given root node.\n     *\n     * This method also wraps whitelisted legacy template extensions\n     * (`is=\"dom-if\"` and `is=\"dom-repeat\"`) with their equivalent element\n     * wrappers, collapses text nodes, and strips whitespace from the template\n     * if the `templateInfo.stripWhitespace` setting was provided.\n     *\n     * @param {Node} root Root node whose `childNodes` will be parsed\n     * @param {!TemplateInfo} templateInfo Template metadata for current template\n     * @param {!NodeInfo} nodeInfo Node metadata for current template.\n     * @return {void}\n     */\n    static _parseTemplateChildNodes(root, templateInfo, nodeInfo) {\n      if (root.localName === 'script' || root.localName === 'style') {\n        return;\n      }\n      for (let node=root.firstChild, parentIndex=0, next; node; node=next) {\n        // Wrap templates\n        if (node.localName == 'template') {\n          node = wrapTemplateExtension(node);\n        }\n        // collapse adjacent textNodes: fixes an IE issue that can cause\n        // text nodes to be inexplicably split =(\n        // note that root.normalize() should work but does not so we do this\n        // manually.\n        next = node.nextSibling;\n        if (node.nodeType === Node.TEXT_NODE) {\n          let /** Node */ n = next;\n          while (n && (n.nodeType === Node.TEXT_NODE)) {\n            node.textContent += n.textContent;\n            next = n.nextSibling;\n            root.removeChild(n);\n            n = next;\n          }\n          // optionally strip whitespace\n          if (templateInfo.stripWhiteSpace && !node.textContent.trim()) {\n            root.removeChild(node);\n            continue;\n          }\n        }\n        let childInfo =\n            /** @type {!NodeInfo} */ ({parentIndex, parentInfo: nodeInfo});\n        if (this._parseTemplateNode(node, templateInfo, childInfo)) {\n          childInfo.infoIndex = templateInfo.nodeInfoList.push(childInfo) - 1;\n        }\n        // Increment if not removed\n        if (node.parentNode) {\n          parentIndex++;\n        }\n      }\n    }\n\n    /**\n     * Parses template content for the given nested `<template>`.\n     *\n     * Nested template info is stored as `templateInfo` in the current node's\n     * `nodeInfo`. `template.content` is removed and stored in `templateInfo`.\n     * It will then be the responsibility of the host to set it back to the\n     * template and for users stamping nested templates to use the\n     * `_contentForTemplate` method to retrieve the content for this template\n     * (an optimization to avoid the cost of cloning nested template content).\n     *\n     * @param {HTMLTemplateElement} node Node to parse (a <template>)\n     * @param {TemplateInfo} outerTemplateInfo Template metadata for current template\n     *   that includes the template `node`\n     * @param {!NodeInfo} nodeInfo Node metadata for current template.\n     * @return {boolean} `true` if the visited node added node-specific\n     *   metadata to `nodeInfo`\n     * @nocollapse\n     */\n    static _parseTemplateNestedTemplate(node, outerTemplateInfo, nodeInfo) {\n      // TODO(rictic): the type of node should be non-null\n      let element = /** @type {!HTMLTemplateElement} */ (node);\n      let templateInfo = this._parseTemplate(element, outerTemplateInfo);\n      let content = templateInfo.content =\n          element.content.ownerDocument.createDocumentFragment();\n      content.appendChild(element.content);\n      nodeInfo.templateInfo = templateInfo;\n      return true;\n    }\n\n    /**\n     * Parses template node attributes and adds node metadata to `nodeInfo`\n     * for nodes of interest.\n     *\n     * @param {Element} node Node to parse\n     * @param {!TemplateInfo} templateInfo Template metadata for current\n     *     template\n     * @param {!NodeInfo} nodeInfo Node metadata for current template.\n     * @return {boolean} `true` if the visited node added node-specific\n     *   metadata to `nodeInfo`\n     * @nocollapse\n     */\n    static _parseTemplateNodeAttributes(node, templateInfo, nodeInfo) {\n      // Make copy of original attribute list, since the order may change\n      // as attributes are added and removed\n      let noted = false;\n      let attrs = Array.from(node.attributes);\n      for (let i=attrs.length-1, a; (a=attrs[i]); i--) {\n        noted = this._parseTemplateNodeAttribute(node, templateInfo, nodeInfo, a.name, a.value) || noted;\n      }\n      return noted;\n    }\n\n    /**\n     * Parses a single template node attribute and adds node metadata to\n     * `nodeInfo` for attributes of interest.\n     *\n     * This implementation adds metadata for `on-event=\"handler\"` attributes\n     * and `id` attributes.\n     *\n     * @param {Element} node Node to parse\n     * @param {!TemplateInfo} templateInfo Template metadata for current template\n     * @param {!NodeInfo} nodeInfo Node metadata for current template.\n     * @param {string} name Attribute name\n     * @param {string} value Attribute value\n     * @return {boolean} `true` if the visited node added node-specific\n     *   metadata to `nodeInfo`\n     * @nocollapse\n     */\n    static _parseTemplateNodeAttribute(node, templateInfo, nodeInfo, name, value) {\n      // events (on-*)\n      if (name.slice(0, 3) === 'on-') {\n        node.removeAttribute(name);\n        nodeInfo.events = nodeInfo.events || [];\n        nodeInfo.events.push({\n          name: name.slice(3),\n          value\n        });\n        return true;\n      }\n      // static id\n      else if (name === 'id') {\n        nodeInfo.id = value;\n        return true;\n      }\n      return false;\n    }\n\n    /**\n     * Returns the `content` document fragment for a given template.\n     *\n     * For nested templates, Polymer performs an optimization to cache nested\n     * template content to avoid the cost of cloning deeply nested templates.\n     * This method retrieves the cached content for a given template.\n     *\n     * @param {HTMLTemplateElement} template Template to retrieve `content` for\n     * @return {DocumentFragment} Content fragment\n     * @nocollapse\n     */\n    static _contentForTemplate(template) {\n      let templateInfo = /** @type {HTMLTemplateElementWithInfo} */ (template)._templateInfo;\n      return (templateInfo && templateInfo.content) || template.content;\n    }\n\n    /**\n     * Clones the provided template content and returns a document fragment\n     * containing the cloned dom.\n     *\n     * The template is parsed (once and memoized) using this library's\n     * template parsing features, and provides the following value-added\n     * features:\n     * * Adds declarative event listeners for `on-event=\"handler\"` attributes\n     * * Generates an \"id map\" for all nodes with id's under `$` on returned\n     *   document fragment\n     * * Passes template info including `content` back to templates as\n     *   `_templateInfo` (a performance optimization to avoid deep template\n     *   cloning)\n     *\n     * Note that the memoized template parsing process is destructive to the\n     * template: attributes for bindings and declarative event listeners are\n     * removed after being noted in notes, and any nested `<template>.content`\n     * is removed and stored in notes as well.\n     *\n     * @param {!HTMLTemplateElement} template Template to stamp\n     * @param {TemplateInfo=} templateInfo Optional template info associated\n     *   with the template to be stamped; if omitted the template will be\n     *   automatically parsed.\n     * @return {!StampedTemplate} Cloned template content\n     * @override\n     */\n    _stampTemplate(template, templateInfo) {\n      // Polyfill support: bootstrap the template if it has not already been\n      if (template && !template.content &&\n          window.HTMLTemplateElement && HTMLTemplateElement.decorate) {\n        HTMLTemplateElement.decorate(template);\n      }\n      // Accepting the `templateInfo` via an argument allows for creating\n      // instances of the `templateInfo` by the caller, useful for adding\n      // instance-time information to the prototypical data\n      templateInfo = templateInfo || this.constructor._parseTemplate(template);\n      let nodeInfo = templateInfo.nodeInfoList;\n      let content = templateInfo.content || template.content;\n      let dom = /** @type {DocumentFragment} */ (document.importNode(content, true));\n      // NOTE: ShadyDom optimization indicating there is an insertion point\n      dom.__noInsertionPoint = !templateInfo.hasInsertionPoint;\n      let nodes = dom.nodeList = new Array(nodeInfo.length);\n      dom.$ = {};\n      for (let i=0, l=nodeInfo.length, info; (i<l) && (info=nodeInfo[i]); i++) {\n        let node = nodes[i] = findTemplateNode(dom, info);\n        applyIdToMap(this, dom.$, node, info);\n        applyTemplateInfo(this, node, info, templateInfo);\n        applyEventListener(this, node, info);\n      }\n      dom = /** @type {!StampedTemplate} */(dom); // eslint-disable-line no-self-assign\n      return dom;\n    }\n\n    /**\n     * Adds an event listener by method name for the event provided.\n     *\n     * This method generates a handler function that looks up the method\n     * name at handling time.\n     *\n     * @param {!EventTarget} node Node to add listener on\n     * @param {string} eventName Name of event\n     * @param {string} methodName Name of method\n     * @param {*=} context Context the method will be called on (defaults\n     *   to `node`)\n     * @return {Function} Generated handler function\n     * @override\n     */\n    _addMethodEventListenerToNode(node, eventName, methodName, context) {\n      context = context || node;\n      let handler = createNodeEventHandler(context, eventName, methodName);\n      this._addEventListenerToNode(node, eventName, handler);\n      return handler;\n    }\n\n    /**\n     * Override point for adding custom or simulated event handling.\n     *\n     * @param {!EventTarget} node Node to add event listener to\n     * @param {string} eventName Name of event\n     * @param {function(!Event):void} handler Listener function to add\n     * @return {void}\n     * @override\n     */\n    _addEventListenerToNode(node, eventName, handler) {\n      node.addEventListener(eventName, handler);\n    }\n\n    /**\n     * Override point for adding custom or simulated event handling.\n     *\n     * @param {!EventTarget} node Node to remove event listener from\n     * @param {string} eventName Name of event\n     * @param {function(!Event):void} handler Listener function to remove\n     * @return {void}\n     * @override\n     */\n    _removeEventListenerFromNode(node, eventName, handler) {\n      node.removeEventListener(eventName, handler);\n    }\n\n  }\n\n  return TemplateStamp;\n\n});\n","/**\n * @fileoverview\n * @suppress {checkPrototypalTypes}\n * @license Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt The complete set of authors may be found\n * at http://polymer.github.io/AUTHORS.txt The complete set of contributors may\n * be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by\n * Google as part of the polymer project is also subject to an additional IP\n * rights grant found at http://polymer.github.io/PATENTS.txt\n */\n\nimport '../utils/boot.js';\nimport { wrap } from '../utils/wrap.js';\nimport { dedupingMixin } from '../utils/mixin.js';\nimport { root, isAncestor, isDescendant, get, translate, isPath, set, normalize } from '../utils/path.js';\n/* for notify, reflect */\nimport { camelToDashCase, dashToCamelCase } from '../utils/case-map.js';\nimport { PropertyAccessors } from './property-accessors.js';\n/* for annotated effects */\nimport { TemplateStamp } from './template-stamp.js';\nimport { sanitizeDOMValue, legacyUndefined, orderedComputed, removeNestedTemplates, fastDomIf } from '../utils/settings.js';\n\n// Monotonically increasing unique ID used for de-duping effects triggered\n// from multiple properties in the same turn\nlet dedupeId = 0;\n\nconst NOOP = [];\n\n/**\n * Property effect types; effects are stored on the prototype using these keys\n * @enum {string}\n */\nconst TYPES = {\n  COMPUTE: '__computeEffects',\n  REFLECT: '__reflectEffects',\n  NOTIFY: '__notifyEffects',\n  PROPAGATE: '__propagateEffects',\n  OBSERVE: '__observeEffects',\n  READ_ONLY: '__readOnly'\n};\n\nconst COMPUTE_INFO = '__computeInfo';\n\n/** @const {!RegExp} */\nconst capitalAttributeRegex = /[A-Z]/;\n\n/**\n * @typedef {{\n * name: (string | undefined),\n * structured: (boolean | undefined),\n * wildcard: (boolean | undefined)\n * }}\n */\nlet DataTrigger; //eslint-disable-line no-unused-vars\n\n/**\n * @typedef {{\n * info: ?,\n * trigger: (!DataTrigger | undefined),\n * fn: (!Function | undefined)\n * }}\n */\nlet DataEffect; //eslint-disable-line no-unused-vars\n\n/**\n * Ensures that the model has an own-property map of effects for the given type.\n * The model may be a prototype or an instance.\n *\n * Property effects are stored as arrays of effects by property in a map,\n * by named type on the model. e.g.\n *\n *   __computeEffects: {\n *     foo: [ ... ],\n *     bar: [ ... ]\n *   }\n *\n * If the model does not yet have an effect map for the type, one is created\n * and returned.  If it does, but it is not an own property (i.e. the\n * prototype had effects), the the map is deeply cloned and the copy is\n * set on the model and returned, ready for new effects to be added.\n *\n * @param {Object} model Prototype or instance\n * @param {string} type Property effect type\n * @param {boolean=} cloneArrays Clone any arrays assigned to the map when\n *   extending a superclass map onto this subclass\n * @return {Object} The own-property map of effects for the given type\n * @private\n */\nfunction ensureOwnEffectMap(model, type, cloneArrays) {\n  let effects = model[type];\n  if (!effects) {\n    effects = model[type] = {};\n  } else if (!model.hasOwnProperty(type)) {\n    effects = model[type] = Object.create(model[type]);\n    if (cloneArrays) {\n      for (let p in effects) {\n        let protoFx = effects[p];\n        // Perf optimization over Array.slice\n        let instFx = effects[p] = Array(protoFx.length);\n        for (let i=0; i<protoFx.length; i++) {\n          instFx[i] = protoFx[i];\n        }\n      }\n    }\n  }\n  return effects;\n}\n\n// -- effects ----------------------------------------------\n\n/**\n * Runs all effects of a given type for the given set of property changes\n * on an instance.\n *\n * @param {!Polymer_PropertyEffects} inst The instance with effects to run\n * @param {?Object} effects Object map of property-to-Array of effects\n * @param {?Object} props Bag of current property changes\n * @param {?Object=} oldProps Bag of previous values for changed properties\n * @param {boolean=} hasPaths True with `props` contains one or more paths\n * @param {*=} extraArgs Additional metadata to pass to effect function\n * @return {boolean} True if an effect ran for this property\n * @private\n */\nfunction runEffects(inst, effects, props, oldProps, hasPaths, extraArgs) {\n  if (effects) {\n    let ran = false;\n    const id = dedupeId++;\n    for (let prop in props) {\n      // Inline `runEffectsForProperty` for perf.\n      let rootProperty = hasPaths ? root(prop) : prop;\n      let fxs = effects[rootProperty];\n      if (fxs) {\n        for (let i=0, l=fxs.length, fx; (i<l) && (fx=fxs[i]); i++) {\n          if ((!fx.info || fx.info.lastRun !== id) &&\n              (!hasPaths || pathMatchesTrigger(prop, fx.trigger))) {\n            if (fx.info) {\n              fx.info.lastRun = id;\n            }\n            fx.fn(inst, prop, props, oldProps, fx.info, hasPaths, extraArgs);\n            ran = true;\n          }\n        }\n      }\n    }\n    return ran;\n  }\n  return false;\n}\n\n/**\n * Runs a list of effects for a given property.\n *\n * @param {!Polymer_PropertyEffects} inst The instance with effects to run\n * @param {!Object} effects Object map of property-to-Array of effects\n * @param {number} dedupeId Counter used for de-duping effects\n * @param {string} prop Name of changed property\n * @param {*} props Changed properties\n * @param {*} oldProps Old properties\n * @param {boolean=} hasPaths True with `props` contains one or more paths\n * @param {*=} extraArgs Additional metadata to pass to effect function\n * @return {boolean} True if an effect ran for this property\n * @private\n */\nfunction runEffectsForProperty(inst, effects, dedupeId, prop, props, oldProps, hasPaths, extraArgs) {\n  let ran = false;\n  let rootProperty = hasPaths ? root(prop) : prop;\n  let fxs = effects[rootProperty];\n  if (fxs) {\n    for (let i=0, l=fxs.length, fx; (i<l) && (fx=fxs[i]); i++) {\n      if ((!fx.info || fx.info.lastRun !== dedupeId) &&\n          (!hasPaths || pathMatchesTrigger(prop, fx.trigger))) {\n        if (fx.info) {\n          fx.info.lastRun = dedupeId;\n        }\n        fx.fn(inst, prop, props, oldProps, fx.info, hasPaths, extraArgs);\n        ran = true;\n      }\n    }\n  }\n  return ran;\n}\n\n/**\n * Determines whether a property/path that has changed matches the trigger\n * criteria for an effect.  A trigger is a descriptor with the following\n * structure, which matches the descriptors returned from `parseArg`.\n * e.g. for `foo.bar.*`:\n * ```\n * trigger: {\n *   name: 'a.b',\n *   structured: true,\n *   wildcard: true\n * }\n * ```\n * If no trigger is given, the path is deemed to match.\n *\n * @param {string} path Path or property that changed\n * @param {?DataTrigger} trigger Descriptor\n * @return {boolean} Whether the path matched the trigger\n */\nfunction pathMatchesTrigger(path, trigger) {\n  if (trigger) {\n    let triggerPath = /** @type {string} */ (trigger.name);\n    return (triggerPath == path) ||\n        !!(trigger.structured && isAncestor(triggerPath, path)) ||\n        !!(trigger.wildcard && isDescendant(triggerPath, path));\n  } else {\n    return true;\n  }\n}\n\n/**\n * Implements the \"observer\" effect.\n *\n * Calls the method with `info.methodName` on the instance, passing the\n * new and old values.\n *\n * @param {!Polymer_PropertyEffects} inst The instance the effect will be run on\n * @param {string} property Name of property\n * @param {Object} props Bag of current property changes\n * @param {Object} oldProps Bag of previous values for changed properties\n * @param {?} info Effect metadata\n * @return {void}\n * @private\n */\nfunction runObserverEffect(inst, property, props, oldProps, info) {\n  let fn = typeof info.method === \"string\" ? inst[info.method] : info.method;\n  let changedProp = info.property;\n  if (fn) {\n    fn.call(inst, inst.__data[changedProp], oldProps[changedProp]);\n  } else if (!info.dynamicFn) {\n    console.warn('observer method `' + info.method + '` not defined');\n  }\n}\n\n/**\n * Runs \"notify\" effects for a set of changed properties.\n *\n * This method differs from the generic `runEffects` method in that it\n * will dispatch path notification events in the case that the property\n * changed was a path and the root property for that path didn't have a\n * \"notify\" effect.  This is to maintain 1.0 behavior that did not require\n * `notify: true` to ensure object sub-property notifications were\n * sent.\n *\n * @param {!Polymer_PropertyEffects} inst The instance with effects to run\n * @param {Object} notifyProps Bag of properties to notify\n * @param {Object} props Bag of current property changes\n * @param {Object} oldProps Bag of previous values for changed properties\n * @param {boolean} hasPaths True with `props` contains one or more paths\n * @return {void}\n * @private\n */\nfunction runNotifyEffects(inst, notifyProps, props, oldProps, hasPaths) {\n  // Notify\n  let fxs = inst[TYPES.NOTIFY];\n  let notified;\n  let id = dedupeId++;\n  // Try normal notify effects; if none, fall back to try path notification\n  for (let prop in notifyProps) {\n    if (notifyProps[prop]) {\n      if (fxs && runEffectsForProperty(inst, fxs, id, prop, props, oldProps, hasPaths)) {\n        notified = true;\n      } else if (hasPaths && notifyPath(inst, prop, props)) {\n        notified = true;\n      }\n    }\n  }\n  // Flush host if we actually notified and host was batching\n  // And the host has already initialized clients; this prevents\n  // an issue with a host observing data changes before clients are ready.\n  let host;\n  if (notified && (host = inst.__dataHost) && host._invalidateProperties) {\n    host._invalidateProperties();\n  }\n}\n\n/**\n * Dispatches {property}-changed events with path information in the detail\n * object to indicate a sub-path of the property was changed.\n *\n * @param {!Polymer_PropertyEffects} inst The element from which to fire the\n *     event\n * @param {string} path The path that was changed\n * @param {Object} props Bag of current property changes\n * @return {boolean} Returns true if the path was notified\n * @private\n */\nfunction notifyPath(inst, path, props) {\n  let rootProperty = root(path);\n  if (rootProperty !== path) {\n    let eventName = camelToDashCase(rootProperty) + '-changed';\n    dispatchNotifyEvent(inst, eventName, props[path], path);\n    return true;\n  }\n  return false;\n}\n\n/**\n * Dispatches {property}-changed events to indicate a property (or path)\n * changed.\n *\n * @param {!Polymer_PropertyEffects} inst The element from which to fire the\n *     event\n * @param {string} eventName The name of the event to send\n *     ('{property}-changed')\n * @param {*} value The value of the changed property\n * @param {string | null | undefined} path If a sub-path of this property\n *     changed, the path that changed (optional).\n * @return {void}\n * @private\n * @suppress {invalidCasts}\n */\nfunction dispatchNotifyEvent(inst, eventName, value, path) {\n  let detail = {\n    value: value,\n    queueProperty: true\n  };\n  if (path) {\n    detail.path = path;\n  }\n  // As a performance optimization, we could elide the wrap here since notifying\n  // events are non-bubbling and shouldn't need retargeting. However, a very\n  // small number of internal tests failed in obscure ways, which may indicate\n  // user code relied on timing differences resulting from ShadyDOM flushing\n  // as a result of the wrapped `dispatchEvent`.\n  wrap(/** @type {!HTMLElement} */(inst)).dispatchEvent(new CustomEvent(eventName, { detail }));\n}\n\n/**\n * Implements the \"notify\" effect.\n *\n * Dispatches a non-bubbling event named `info.eventName` on the instance\n * with a detail object containing the new `value`.\n *\n * @param {!Polymer_PropertyEffects} inst The instance the effect will be run on\n * @param {string} property Name of property\n * @param {Object} props Bag of current property changes\n * @param {Object} oldProps Bag of previous values for changed properties\n * @param {?} info Effect metadata\n * @param {boolean} hasPaths True with `props` contains one or more paths\n * @return {void}\n * @private\n */\nfunction runNotifyEffect(inst, property, props, oldProps, info, hasPaths) {\n  let rootProperty = hasPaths ? root(property) : property;\n  let path = rootProperty != property ? property : null;\n  let value = path ? get(inst, path) : inst.__data[property];\n  if (path && value === undefined) {\n    value = props[property];  // specifically for .splices\n  }\n  dispatchNotifyEvent(inst, info.eventName, value, path);\n}\n\n/**\n * Handler function for 2-way notification events. Receives context\n * information captured in the `addNotifyListener` closure from the\n * `__notifyListeners` metadata.\n *\n * Sets the value of the notified property to the host property or path.  If\n * the event contained path information, translate that path to the host\n * scope's name for that path first.\n *\n * @param {CustomEvent} event Notification event (e.g. '<property>-changed')\n * @param {!Polymer_PropertyEffects} inst Host element instance handling the\n *     notification event\n * @param {string} fromProp Child element property that was bound\n * @param {string} toPath Host property/path that was bound\n * @param {boolean} negate Whether the binding was negated\n * @return {void}\n * @private\n */\nfunction handleNotification(event, inst, fromProp, toPath, negate) {\n  let value;\n  let detail = /** @type {Object} */(event.detail);\n  let fromPath = detail && detail.path;\n  if (fromPath) {\n    toPath = translate(fromProp, toPath, fromPath);\n    value = detail && detail.value;\n  } else {\n    value = event.currentTarget[fromProp];\n  }\n  value = negate ? !value : value;\n  if (!inst[TYPES.READ_ONLY] || !inst[TYPES.READ_ONLY][toPath]) {\n    if (inst._setPendingPropertyOrPath(toPath, value, true, Boolean(fromPath))\n      && (!detail || !detail.queueProperty)) {\n      inst._invalidateProperties();\n    }\n  }\n}\n\n/**\n * Implements the \"reflect\" effect.\n *\n * Sets the attribute named `info.attrName` to the given property value.\n *\n * @param {!Polymer_PropertyEffects} inst The instance the effect will be run on\n * @param {string} property Name of property\n * @param {Object} props Bag of current property changes\n * @param {Object} oldProps Bag of previous values for changed properties\n * @param {?} info Effect metadata\n * @return {void}\n * @private\n */\nfunction runReflectEffect(inst, property, props, oldProps, info) {\n  let value = inst.__data[property];\n  if (sanitizeDOMValue) {\n    value = sanitizeDOMValue(value, info.attrName, 'attribute', /** @type {Node} */(inst));\n  }\n  inst._propertyToAttribute(property, info.attrName, value);\n}\n\n/**\n * Runs \"computed\" effects for a set of changed properties.\n *\n * This method differs from the generic `runEffects` method in that it\n * continues to run computed effects based on the output of each pass until\n * there are no more newly computed properties.  This ensures that all\n * properties that will be computed by the initial set of changes are\n * computed before other effects (binding propagation, observers, and notify)\n * run.\n *\n * @param {!Polymer_PropertyEffects} inst The instance the effect will be run on\n * @param {?Object} changedProps Bag of changed properties\n * @param {?Object} oldProps Bag of previous values for changed properties\n * @param {boolean} hasPaths True with `props` contains one or more paths\n * @return {void}\n * @private\n */\nfunction runComputedEffects(inst, changedProps, oldProps, hasPaths) {\n  let computeEffects = inst[TYPES.COMPUTE];\n  if (computeEffects) {\n    if (orderedComputed) {\n      // Runs computed effects in efficient order by keeping a topologically-\n      // sorted queue of compute effects to run, and inserting subsequently\n      // invalidated effects as they are run\n      dedupeId++;\n      const order = getComputedOrder(inst);\n      const queue = [];\n      for (let p in changedProps) {\n        enqueueEffectsFor(p, computeEffects, queue, order, hasPaths);\n      }\n      let info;\n      while ((info = queue.shift())) {\n        if (runComputedEffect(inst, '', changedProps, oldProps, info)) {\n          enqueueEffectsFor(info.methodInfo, computeEffects, queue, order, hasPaths);\n        }\n      }\n      Object.assign(/** @type {!Object} */ (oldProps), inst.__dataOld);\n      Object.assign(/** @type {!Object} */ (changedProps), inst.__dataPending);\n      inst.__dataPending = null;\n    } else {\n      // Original Polymer 2.x computed effects order, which continues running\n      // effects until no further computed properties have been invalidated\n      let inputProps = changedProps;\n      while (runEffects(inst, computeEffects, inputProps, oldProps, hasPaths)) {\n        Object.assign(/** @type {!Object} */ (oldProps), inst.__dataOld);\n        Object.assign(/** @type {!Object} */ (changedProps), inst.__dataPending);\n        inputProps = inst.__dataPending;\n        inst.__dataPending = null;\n      }\n    }\n  }\n}\n\n/**\n * Inserts a computed effect into a queue, given the specified order. Performs\n * the insert using a binary search.\n *\n * Used by `orderedComputed: true` computed property algorithm.\n *\n * @param {Object} info Property effects metadata\n * @param {Array<Object>} queue Ordered queue of effects\n * @param {Map<string,number>} order Map of computed property name->topological\n *   sort order\n */\nconst insertEffect = (info, queue, order) => {\n  let start = 0;\n  let end = queue.length - 1;\n  let idx = -1;\n  while (start <= end) {\n    const mid = (start + end) >> 1;\n    // Note `methodInfo` is where the computed property name is stored in\n    // the effect metadata\n    const cmp = order.get(queue[mid].methodInfo) - order.get(info.methodInfo);\n    if (cmp < 0) {\n      start = mid + 1;\n    } else if (cmp > 0) {\n      end = mid - 1;\n    } else {\n      idx = mid;\n      break;\n    }\n  }\n  if (idx < 0) {\n    idx = end + 1;\n  }\n  queue.splice(idx, 0, info);\n};\n\n/**\n * Inserts all downstream computed effects invalidated by the specified property\n * into the topologically-sorted queue of effects to be run.\n *\n * Used by `orderedComputed: true` computed property algorithm.\n *\n * @param {string} prop Property name\n * @param {Object} computeEffects Computed effects for this element\n * @param {Array<Object>} queue Topologically-sorted queue of computed effects\n *   to be run\n * @param {Map<string,number>} order Map of computed property name->topological\n *   sort order\n * @param {boolean} hasPaths True with `changedProps` contains one or more paths\n */\nconst enqueueEffectsFor = (prop, computeEffects, queue, order, hasPaths) => {\n  const rootProperty = hasPaths ? root(prop) : prop;\n  const fxs = computeEffects[rootProperty];\n  if (fxs) {\n    for (let i=0; i<fxs.length; i++) {\n      const fx = fxs[i];\n      if ((fx.info.lastRun !== dedupeId) &&\n          (!hasPaths || pathMatchesTrigger(prop, fx.trigger))) {\n        fx.info.lastRun = dedupeId;\n        insertEffect(fx.info, queue, order);\n      }\n    }\n  }\n};\n\n/**\n * Generates and retrieves a memoized map of computed property name to its\n * topologically-sorted order.\n *\n * The map is generated by first assigning a \"dependency count\" to each property\n * (defined as number properties it depends on, including its method for\n * \"dynamic functions\"). Any properties that have no dependencies are added to\n * the `ready` queue, which are properties whose order can be added to the final\n * order map. Properties are popped off the `ready` queue one by one and a.) added as\n * the next property in the order map, and b.) each property that it is a\n * dependency for has its dep count decremented (and if that property's dep\n * count goes to zero, it is added to the `ready` queue), until all properties\n * have been visited and ordered.\n *\n * Used by `orderedComputed: true` computed property algorithm.\n *\n * @param {!Polymer_PropertyEffects} inst The instance to retrieve the computed\n *   effect order for.\n * @return {Map<string,number>} Map of computed property name->topological sort\n *   order\n */\nfunction getComputedOrder(inst) {\n  let ordered = inst.constructor.__orderedComputedDeps;\n  if (!ordered) {\n    ordered = new Map();\n    const effects = inst[TYPES.COMPUTE];\n    let {counts, ready, total} = dependencyCounts(inst);\n    let curr;\n    while ((curr = ready.shift())) {\n      ordered.set(curr, ordered.size);\n      const computedByCurr = effects[curr];\n      if (computedByCurr) {\n        computedByCurr.forEach(fx => {\n          // Note `methodInfo` is where the computed property name is stored\n          const computedProp = fx.info.methodInfo;\n          --total;\n          if (--counts[computedProp] === 0) {\n            ready.push(computedProp);\n          }\n        });\n      }\n    }\n    if (total !== 0) {\n      const el = /** @type {HTMLElement} */ (inst);\n      console.warn(`Computed graph for ${el.localName} incomplete; circular?`);\n    }\n    inst.constructor.__orderedComputedDeps = ordered;\n  }\n  return ordered;\n}\n\n/**\n * Generates a map of property-to-dependency count (`counts`, where \"dependency\n * count\" is the number of dependencies a given property has assuming it is a\n * computed property, otherwise 0).  It also returns a pre-populated list of\n * `ready` properties that have no dependencies and a `total` count, which is\n * used for error-checking the graph.\n *\n * Used by `orderedComputed: true` computed property algorithm.\n *\n * @param {!Polymer_PropertyEffects} inst The instance to generate dependency\n *   counts for.\n * @return {!Object} Object containing `counts` map (property-to-dependency\n *   count) and pre-populated `ready` array of properties that had zero\n *   dependencies.\n */\nfunction dependencyCounts(inst) {\n  const infoForComputed = inst[COMPUTE_INFO];\n  const counts = {};\n  const computedDeps = inst[TYPES.COMPUTE];\n  const ready = [];\n  let total = 0;\n  // Count dependencies for each computed property\n  for (let p in infoForComputed) {\n    const info = infoForComputed[p];\n    // Be sure to add the method name itself in case of \"dynamic functions\"\n    total += counts[p] =\n      info.args.filter(a => !a.literal).length + (info.dynamicFn ? 1 : 0);\n  }\n  // Build list of ready properties (that aren't themselves computed)\n  for (let p in computedDeps) {\n    if (!infoForComputed[p]) {\n      ready.push(p);\n    }\n  }\n  return {counts, ready, total};\n}\n\n/**\n * Implements the \"computed property\" effect by running the method with the\n * values of the arguments specified in the `info` object and setting the\n * return value to the computed property specified.\n *\n * @param {!Polymer_PropertyEffects} inst The instance the effect will be run on\n * @param {string} property Name of property\n * @param {?Object} changedProps Bag of current property changes\n * @param {?Object} oldProps Bag of previous values for changed properties\n * @param {?} info Effect metadata\n * @return {boolean} True when the property being computed changed\n * @private\n */\nfunction runComputedEffect(inst, property, changedProps, oldProps, info) {\n  // Dirty check dependencies and run if any invalid\n  let result = runMethodEffect(inst, property, changedProps, oldProps, info);\n  // Abort if method returns a no-op result\n  if (result === NOOP) {\n    return false;\n  }\n  let computedProp = info.methodInfo;\n  if (inst.__dataHasAccessor && inst.__dataHasAccessor[computedProp]) {\n    return inst._setPendingProperty(computedProp, result, true);\n  } else {\n    inst[computedProp] = result;\n    return false;\n  }\n}\n\n/**\n * Computes path changes based on path links set up using the `linkPaths`\n * API.\n *\n * @param {!Polymer_PropertyEffects} inst The instance whose props are changing\n * @param {string} path Path that has changed\n * @param {*} value Value of changed path\n * @return {void}\n * @private\n */\nfunction computeLinkedPaths(inst, path, value) {\n  let links = inst.__dataLinkedPaths;\n  if (links) {\n    let link;\n    for (let a in links) {\n      let b = links[a];\n      if (isDescendant(a, path)) {\n        link = translate(a, b, path);\n        inst._setPendingPropertyOrPath(link, value, true, true);\n      } else if (isDescendant(b, path)) {\n        link = translate(b, a, path);\n        inst._setPendingPropertyOrPath(link, value, true, true);\n      }\n    }\n  }\n}\n\n// -- bindings ----------------------------------------------\n\n/**\n * Adds binding metadata to the current `nodeInfo`, and binding effects\n * for all part dependencies to `templateInfo`.\n *\n * @param {Function} constructor Class that `_parseTemplate` is currently\n *   running on\n * @param {TemplateInfo} templateInfo Template metadata for current template\n * @param {NodeInfo} nodeInfo Node metadata for current template node\n * @param {string} kind Binding kind, either 'property', 'attribute', or 'text'\n * @param {string} target Target property name\n * @param {!Array<!BindingPart>} parts Array of binding part metadata\n * @param {string=} literal Literal text surrounding binding parts (specified\n *   only for 'property' bindings, since these must be initialized as part\n *   of boot-up)\n * @return {void}\n * @private\n */\nfunction addBinding(constructor, templateInfo, nodeInfo, kind, target, parts, literal) {\n  // Create binding metadata and add to nodeInfo\n  nodeInfo.bindings = nodeInfo.bindings || [];\n  let /** Binding */ binding = { kind, target, parts, literal, isCompound: (parts.length !== 1) };\n  nodeInfo.bindings.push(binding);\n  // Add listener info to binding metadata\n  if (shouldAddListener(binding)) {\n    let {event, negate} = binding.parts[0];\n    binding.listenerEvent = event || (camelToDashCase(target) + '-changed');\n    binding.listenerNegate = negate;\n  }\n  // Add \"propagate\" property effects to templateInfo\n  let index = templateInfo.nodeInfoList.length;\n  for (let i=0; i<binding.parts.length; i++) {\n    let part = binding.parts[i];\n    part.compoundIndex = i;\n    addEffectForBindingPart(constructor, templateInfo, binding, part, index);\n  }\n}\n\n/**\n * Adds property effects to the given `templateInfo` for the given binding\n * part.\n *\n * @param {Function} constructor Class that `_parseTemplate` is currently\n *   running on\n * @param {TemplateInfo} templateInfo Template metadata for current template\n * @param {!Binding} binding Binding metadata\n * @param {!BindingPart} part Binding part metadata\n * @param {number} index Index into `nodeInfoList` for this node\n * @return {void}\n */\nfunction addEffectForBindingPart(constructor, templateInfo, binding, part, index) {\n  if (!part.literal) {\n    if (binding.kind === 'attribute' && binding.target[0] === '-') {\n      console.warn('Cannot set attribute ' + binding.target +\n        ' because \"-\" is not a valid attribute starting character');\n    } else {\n      let dependencies = part.dependencies;\n      let info = { index, binding, part, evaluator: constructor };\n      for (let j=0; j<dependencies.length; j++) {\n        let trigger = dependencies[j];\n        if (typeof trigger == 'string') {\n          trigger = parseArg(trigger);\n          trigger.wildcard = true;\n        }\n        constructor._addTemplatePropertyEffect(templateInfo, trigger.rootProperty, {\n          fn: runBindingEffect,\n          info, trigger\n        });\n      }\n    }\n  }\n}\n\n/**\n * Implements the \"binding\" (property/path binding) effect.\n *\n * Note that binding syntax is overridable via `_parseBindings` and\n * `_evaluateBinding`.  This method will call `_evaluateBinding` for any\n * non-literal parts returned from `_parseBindings`.  However,\n * there is no support for _path_ bindings via custom binding parts,\n * as this is specific to Polymer's path binding syntax.\n *\n * @param {!Polymer_PropertyEffects} inst The instance the effect will be run on\n * @param {string} path Name of property\n * @param {Object} props Bag of current property changes\n * @param {Object} oldProps Bag of previous values for changed properties\n * @param {?} info Effect metadata\n * @param {boolean} hasPaths True with `props` contains one or more paths\n * @param {Array} nodeList List of nodes associated with `nodeInfoList` template\n *   metadata\n * @return {void}\n * @private\n */\nfunction runBindingEffect(inst, path, props, oldProps, info, hasPaths, nodeList) {\n  let node = nodeList[info.index];\n  let binding = info.binding;\n  let part = info.part;\n  // Subpath notification: transform path and set to client\n  // e.g.: foo=\"{{obj.sub}}\", path: 'obj.sub.prop', set 'foo.prop'=obj.sub.prop\n  if (hasPaths && part.source && (path.length > part.source.length) &&\n      (binding.kind == 'property') && !binding.isCompound &&\n      node.__isPropertyEffectsClient &&\n      node.__dataHasAccessor && node.__dataHasAccessor[binding.target]) {\n    let value = props[path];\n    path = translate(part.source, binding.target, path);\n    if (node._setPendingPropertyOrPath(path, value, false, true)) {\n      inst._enqueueClient(node);\n    }\n  } else {\n    let value = info.evaluator._evaluateBinding(inst, part, path, props, oldProps, hasPaths);\n    // Propagate value to child\n    // Abort if value is a no-op result\n    if (value !== NOOP) {\n      applyBindingValue(inst, node, binding, part, value);\n    }\n  }\n}\n\n/**\n * Sets the value for an \"binding\" (binding) effect to a node,\n * either as a property or attribute.\n *\n * @param {!Polymer_PropertyEffects} inst The instance owning the binding effect\n * @param {Node} node Target node for binding\n * @param {!Binding} binding Binding metadata\n * @param {!BindingPart} part Binding part metadata\n * @param {*} value Value to set\n * @return {void}\n * @private\n */\nfunction applyBindingValue(inst, node, binding, part, value) {\n  value = computeBindingValue(node, value, binding, part);\n  if (sanitizeDOMValue) {\n    value = sanitizeDOMValue(value, binding.target, binding.kind, node);\n  }\n  if (binding.kind == 'attribute') {\n    // Attribute binding\n    inst._valueToNodeAttribute(/** @type {Element} */(node), value, binding.target);\n  } else {\n    // Property binding\n    let prop = binding.target;\n    if (node.__isPropertyEffectsClient &&\n        node.__dataHasAccessor && node.__dataHasAccessor[prop]) {\n      if (!node[TYPES.READ_ONLY] || !node[TYPES.READ_ONLY][prop]) {\n        if (node._setPendingProperty(prop, value)) {\n          inst._enqueueClient(node);\n        }\n      }\n    } else {\n      // In legacy no-batching mode, bindings applied before dataReady are\n      // equivalent to the \"apply config\" phase, which only set managed props\n      inst._setUnmanagedPropertyToNode(node, prop, value);\n    }\n  }\n}\n\n/**\n * Transforms an \"binding\" effect value based on compound & negation\n * effect metadata, as well as handling for special-case properties\n *\n * @param {Node} node Node the value will be set to\n * @param {*} value Value to set\n * @param {!Binding} binding Binding metadata\n * @param {!BindingPart} part Binding part metadata\n * @return {*} Transformed value to set\n * @private\n */\nfunction computeBindingValue(node, value, binding, part) {\n  if (binding.isCompound) {\n    let storage = node.__dataCompoundStorage[binding.target];\n    storage[part.compoundIndex] = value;\n    value = storage.join('');\n  }\n  if (binding.kind !== 'attribute') {\n    // Some browsers serialize `undefined` to `\"undefined\"`\n    if (binding.target === 'textContent' ||\n        (binding.target === 'value' &&\n          (node.localName === 'input' || node.localName === 'textarea'))) {\n      value = value == undefined ? '' : value;\n    }\n  }\n  return value;\n}\n\n/**\n * Returns true if a binding's metadata meets all the requirements to allow\n * 2-way binding, and therefore a `<property>-changed` event listener should be\n * added:\n * - used curly braces\n * - is a property (not attribute) binding\n * - is not a textContent binding\n * - is not compound\n *\n * @param {!Binding} binding Binding metadata\n * @return {boolean} True if 2-way listener should be added\n * @private\n */\nfunction shouldAddListener(binding) {\n  return Boolean(binding.target) &&\n         binding.kind != 'attribute' &&\n         binding.kind != 'text' &&\n         !binding.isCompound &&\n         binding.parts[0].mode === '{';\n}\n\n/**\n * Setup compound binding storage structures, notify listeners, and dataHost\n * references onto the bound nodeList.\n *\n * @param {!Polymer_PropertyEffects} inst Instance that bas been previously\n *     bound\n * @param {TemplateInfo} templateInfo Template metadata\n * @return {void}\n * @private\n */\nfunction setupBindings(inst, templateInfo) {\n  // Setup compound storage, dataHost, and notify listeners\n  let {nodeList, nodeInfoList} = templateInfo;\n  if (nodeInfoList.length) {\n    for (let i=0; i < nodeInfoList.length; i++) {\n      let info = nodeInfoList[i];\n      let node = nodeList[i];\n      let bindings = info.bindings;\n      if (bindings) {\n        for (let i=0; i<bindings.length; i++) {\n          let binding = bindings[i];\n          setupCompoundStorage(node, binding);\n          addNotifyListener(node, inst, binding);\n        }\n      }\n      // This ensures all bound elements have a host set, regardless\n      // of whether they upgrade synchronous to creation\n      node.__dataHost = inst;\n    }\n  }\n}\n\n/**\n * Initializes `__dataCompoundStorage` local storage on a bound node with\n * initial literal data for compound bindings, and sets the joined\n * literal parts to the bound property.\n *\n * When changes to compound parts occur, they are first set into the compound\n * storage array for that property, and then the array is joined to result in\n * the final value set to the property/attribute.\n *\n * @param {Node} node Bound node to initialize\n * @param {Binding} binding Binding metadata\n * @return {void}\n * @private\n */\nfunction setupCompoundStorage(node, binding) {\n  if (binding.isCompound) {\n    // Create compound storage map\n    let storage = node.__dataCompoundStorage ||\n      (node.__dataCompoundStorage = {});\n    let parts = binding.parts;\n    // Copy literals from parts into storage for this binding\n    let literals = new Array(parts.length);\n    for (let j=0; j<parts.length; j++) {\n      literals[j] = parts[j].literal;\n    }\n    let target = binding.target;\n    storage[target] = literals;\n    // Configure properties with their literal parts\n    if (binding.literal && binding.kind == 'property') {\n      // Note, className needs style scoping so this needs wrapping.\n      // We may also want to consider doing this for `textContent` and\n      // `innerHTML`.\n      if (target === 'className') {\n        node = wrap(node);\n      }\n      node[target] = binding.literal;\n    }\n  }\n}\n\n/**\n * Adds a 2-way binding notification event listener to the node specified\n *\n * @param {Object} node Child element to add listener to\n * @param {!Polymer_PropertyEffects} inst Host element instance to handle\n *     notification event\n * @param {Binding} binding Binding metadata\n * @return {void}\n * @private\n */\nfunction addNotifyListener(node, inst, binding) {\n  if (binding.listenerEvent) {\n    let part = binding.parts[0];\n    node.addEventListener(binding.listenerEvent, function(e) {\n      handleNotification(e, inst, binding.target, part.source, part.negate);\n    });\n  }\n}\n\n// -- for method-based effects (complexObserver & computed) --------------\n\n/**\n * Adds property effects for each argument in the method signature (and\n * optionally, for the method name if `dynamic` is true) that calls the\n * provided effect function.\n *\n * @param {Element | Object} model Prototype or instance\n * @param {!MethodSignature} sig Method signature metadata\n * @param {string} type Type of property effect to add\n * @param {Function} effectFn Function to run when arguments change\n * @param {*=} methodInfo Effect-specific information to be included in\n *   method effect metadata\n * @param {boolean|Object=} dynamicFn Boolean or object map indicating whether\n *   method names should be included as a dependency to the effect. Note,\n *   defaults to true if the signature is static (sig.static is true).\n * @return {!Object} Effect metadata for this method effect\n * @private\n */\nfunction createMethodEffect(model, sig, type, effectFn, methodInfo, dynamicFn) {\n  dynamicFn = sig.static || (dynamicFn &&\n    (typeof dynamicFn !== 'object' || dynamicFn[sig.methodName]));\n  let info = {\n    methodName: sig.methodName,\n    args: sig.args,\n    methodInfo,\n    dynamicFn\n  };\n  for (let i=0, arg; (i<sig.args.length) && (arg=sig.args[i]); i++) {\n    if (!arg.literal) {\n      model._addPropertyEffect(arg.rootProperty, type, {\n        fn: effectFn, info: info, trigger: arg\n      });\n    }\n  }\n  if (dynamicFn) {\n    model._addPropertyEffect(sig.methodName, type, {\n      fn: effectFn, info: info\n    });\n  }\n  return info;\n}\n\n/**\n * Calls a method with arguments marshaled from properties on the instance\n * based on the method signature contained in the effect metadata.\n *\n * Multi-property observers, computed properties, and inline computing\n * functions call this function to invoke the method, then use the return\n * value accordingly.\n *\n * @param {!Polymer_PropertyEffects} inst The instance the effect will be run on\n * @param {string} property Name of property\n * @param {Object} props Bag of current property changes\n * @param {Object} oldProps Bag of previous values for changed properties\n * @param {?} info Effect metadata\n * @return {*} Returns the return value from the method invocation\n * @private\n */\nfunction runMethodEffect(inst, property, props, oldProps, info) {\n  // Instances can optionally have a _methodHost which allows redirecting where\n  // to find methods. Currently used by `templatize`.\n  let context = inst._methodHost || inst;\n  let fn = context[info.methodName];\n  if (fn) {\n    let args = inst._marshalArgs(info.args, property, props);\n    return args === NOOP ? NOOP : fn.apply(context, args);\n  } else if (!info.dynamicFn) {\n    console.warn('method `' + info.methodName + '` not defined');\n  }\n}\n\nconst emptyArray = [];\n\n// Regular expressions used for binding\nconst IDENT  = '(?:' + '[a-zA-Z_$][\\\\w.:$\\\\-*]*' + ')';\nconst NUMBER = '(?:' + '[-+]?[0-9]*\\\\.?[0-9]+(?:[eE][-+]?[0-9]+)?' + ')';\nconst SQUOTE_STRING = '(?:' + '\\'(?:[^\\'\\\\\\\\]|\\\\\\\\.)*\\'' + ')';\nconst DQUOTE_STRING = '(?:' + '\"(?:[^\"\\\\\\\\]|\\\\\\\\.)*\"' + ')';\nconst STRING = '(?:' + SQUOTE_STRING + '|' + DQUOTE_STRING + ')';\nconst ARGUMENT = '(?:(' + IDENT + '|' + NUMBER + '|' +  STRING + ')\\\\s*' + ')';\nconst ARGUMENTS = '(?:' + ARGUMENT + '(?:,\\\\s*' + ARGUMENT + ')*' + ')';\nconst ARGUMENT_LIST = '(?:' + '\\\\(\\\\s*' +\n                              '(?:' + ARGUMENTS + '?' + ')' +\n                            '\\\\)\\\\s*' + ')';\nconst BINDING = '(' + IDENT + '\\\\s*' + ARGUMENT_LIST + '?' + ')'; // Group 3\nconst OPEN_BRACKET = '(\\\\[\\\\[|{{)' + '\\\\s*';\nconst CLOSE_BRACKET = '(?:]]|}})';\nconst NEGATE = '(?:(!)\\\\s*)?'; // Group 2\nconst EXPRESSION = OPEN_BRACKET + NEGATE + BINDING + CLOSE_BRACKET;\nconst bindingRegex = new RegExp(EXPRESSION, \"g\");\n\n/**\n * Create a string from binding parts of all the literal parts\n *\n * @param {!Array<BindingPart>} parts All parts to stringify\n * @return {string} String made from the literal parts\n */\nfunction literalFromParts(parts) {\n  let s = '';\n  for (let i=0; i<parts.length; i++) {\n    let literal = parts[i].literal;\n    s += literal || '';\n  }\n  return s;\n}\n\n/**\n * Parses an expression string for a method signature, and returns a metadata\n * describing the method in terms of `methodName`, `static` (whether all the\n * arguments are literals), and an array of `args`\n *\n * @param {string} expression The expression to parse\n * @return {?MethodSignature} The method metadata object if a method expression was\n *   found, otherwise `undefined`\n * @private\n */\nfunction parseMethod(expression) {\n  // tries to match valid javascript property names\n  let m = expression.match(/([^\\s]+?)\\(([\\s\\S]*)\\)/);\n  if (m) {\n    let methodName = m[1];\n    let sig = { methodName, static: true, args: emptyArray };\n    if (m[2].trim()) {\n      // replace escaped commas with comma entity, split on un-escaped commas\n      let args = m[2].replace(/\\\\,/g, '&comma;').split(',');\n      return parseArgs(args, sig);\n    } else {\n      return sig;\n    }\n  }\n  return null;\n}\n\n/**\n * Parses an array of arguments and sets the `args` property of the supplied\n * signature metadata object. Sets the `static` property to false if any\n * argument is a non-literal.\n *\n * @param {!Array<string>} argList Array of argument names\n * @param {!MethodSignature} sig Method signature metadata object\n * @return {!MethodSignature} The updated signature metadata object\n * @private\n */\nfunction parseArgs(argList, sig) {\n  sig.args = argList.map(function(rawArg) {\n    let arg = parseArg(rawArg);\n    if (!arg.literal) {\n      sig.static = false;\n    }\n    return arg;\n  }, this);\n  return sig;\n}\n\n/**\n * Parses an individual argument, and returns an argument metadata object\n * with the following fields:\n *\n *   {\n *     value: 'prop',        // property/path or literal value\n *     literal: false,       // whether argument is a literal\n *     structured: false,    // whether the property is a path\n *     rootProperty: 'prop', // the root property of the path\n *     wildcard: false       // whether the argument was a wildcard '.*' path\n *   }\n *\n * @param {string} rawArg The string value of the argument\n * @return {!MethodArg} Argument metadata object\n * @private\n */\nfunction parseArg(rawArg) {\n  // clean up whitespace\n  let arg = rawArg.trim()\n    // replace comma entity with comma\n    .replace(/&comma;/g, ',')\n    // repair extra escape sequences; note only commas strictly need\n    // escaping, but we allow any other char to be escaped since its\n    // likely users will do this\n    .replace(/\\\\(.)/g, '$1')\n    ;\n  // basic argument descriptor\n  let a = {\n    name: arg,\n    value: '',\n    literal: false\n  };\n  // detect literal value (must be String or Number)\n  let fc = arg[0];\n  if (fc === '-') {\n    fc = arg[1];\n  }\n  if (fc >= '0' && fc <= '9') {\n    fc = '#';\n  }\n  switch(fc) {\n    case \"'\":\n    case '\"':\n      a.value = arg.slice(1, -1);\n      a.literal = true;\n      break;\n    case '#':\n      a.value = Number(arg);\n      a.literal = true;\n      break;\n  }\n  // if not literal, look for structured path\n  if (!a.literal) {\n    a.rootProperty = root(arg);\n    // detect structured path (has dots)\n    a.structured = isPath(arg);\n    if (a.structured) {\n      a.wildcard = (arg.slice(-2) == '.*');\n      if (a.wildcard) {\n        a.name = arg.slice(0, -2);\n      }\n    }\n  }\n  return a;\n}\n\nfunction getArgValue(data, props, path) {\n  let value = get(data, path);\n  // when data is not stored e.g. `splices`, get the value from changedProps\n  // TODO(kschaaf): Note, this can cause a rare issue where the wildcard\n  // info.value could pull a stale value out of changedProps during a reentrant\n  // change that sets the value back to undefined.\n  // https://github.com/Polymer/polymer/issues/5479\n  if (value === undefined) {\n    value = props[path];\n  }\n  return value;\n}\n\n// data api\n\n/**\n * Sends array splice notifications (`.splices` and `.length`)\n *\n * Note: this implementation only accepts normalized paths\n *\n * @param {!Polymer_PropertyEffects} inst Instance to send notifications to\n * @param {Array} array The array the mutations occurred on\n * @param {string} path The path to the array that was mutated\n * @param {Array} splices Array of splice records\n * @return {void}\n * @private\n */\nfunction notifySplices(inst, array, path, splices) {\n  const splicesData = { indexSplices: splices };\n  // Legacy behavior stored splices in `__data__` so it was *not* ephemeral.\n  // To match this behavior, we store splices directly on the array.\n  if (legacyUndefined && !inst._overrideLegacyUndefined) {\n    array.splices = splicesData;\n  }\n  inst.notifyPath(path + '.splices', splicesData);\n  inst.notifyPath(path + '.length', array.length);\n  // Clear splice data only when it's stored on the array.\n  if (legacyUndefined && !inst._overrideLegacyUndefined) {\n    splicesData.indexSplices = [];\n  }\n}\n\n/**\n * Creates a splice record and sends an array splice notification for\n * the described mutation\n *\n * Note: this implementation only accepts normalized paths\n *\n * @param {!Polymer_PropertyEffects} inst Instance to send notifications to\n * @param {Array} array The array the mutations occurred on\n * @param {string} path The path to the array that was mutated\n * @param {number} index Index at which the array mutation occurred\n * @param {number} addedCount Number of added items\n * @param {Array} removed Array of removed items\n * @return {void}\n * @private\n */\nfunction notifySplice(inst, array, path, index, addedCount, removed) {\n  notifySplices(inst, array, path, [{\n    index: index,\n    addedCount: addedCount,\n    removed: removed,\n    object: array,\n    type: 'splice'\n  }]);\n}\n\n/**\n * Returns an upper-cased version of the string.\n *\n * @param {string} name String to uppercase\n * @return {string} Uppercased string\n * @private\n */\nfunction upper(name) {\n  return name[0].toUpperCase() + name.substring(1);\n}\n\n/**\n * Element class mixin that provides meta-programming for Polymer's template\n * binding and data observation (collectively, \"property effects\") system.\n *\n * This mixin uses provides the following key static methods for adding\n * property effects to an element class:\n * - `addPropertyEffect`\n * - `createPropertyObserver`\n * - `createMethodObserver`\n * - `createNotifyingProperty`\n * - `createReadOnlyProperty`\n * - `createReflectedProperty`\n * - `createComputedProperty`\n * - `bindTemplate`\n *\n * Each method creates one or more property accessors, along with metadata\n * used by this mixin's implementation of `_propertiesChanged` to perform\n * the property effects.\n *\n * Underscored versions of the above methods also exist on the element\n * prototype for adding property effects on instances at runtime.\n *\n * Note that this mixin overrides several `PropertyAccessors` methods, in\n * many cases to maintain guarantees provided by the Polymer 1.x features;\n * notably it changes property accessors to be synchronous by default\n * whereas the default when using `PropertyAccessors` standalone is to be\n * async by default.\n *\n * @mixinFunction\n * @polymer\n * @appliesMixin TemplateStamp\n * @appliesMixin PropertyAccessors\n * @summary Element class mixin that provides meta-programming for Polymer's\n * template binding and data observation system.\n */\nexport const PropertyEffects = dedupingMixin(superClass => {\n\n  /**\n   * @constructor\n   * @implements {Polymer_PropertyAccessors}\n   * @implements {Polymer_TemplateStamp}\n   * @unrestricted\n   * @private\n   */\n  const propertyEffectsBase = TemplateStamp(PropertyAccessors(superClass));\n\n  /**\n   * @polymer\n   * @mixinClass\n   * @implements {Polymer_PropertyEffects}\n   * @extends {propertyEffectsBase}\n   * @unrestricted\n   */\n  class PropertyEffects extends propertyEffectsBase {\n\n    constructor() {\n      super();\n      /** @type {boolean} */\n      // Used to identify users of this mixin, ala instanceof\n      this.__isPropertyEffectsClient = true;\n      /** @type {boolean} */\n      this.__dataClientsReady;\n      /** @type {Array} */\n      this.__dataPendingClients;\n      /** @type {Object} */\n      this.__dataToNotify;\n      /** @type {Object} */\n      this.__dataLinkedPaths;\n      /** @type {boolean} */\n      this.__dataHasPaths;\n      /** @type {Object} */\n      this.__dataCompoundStorage;\n      /** @type {Polymer_PropertyEffects} */\n      this.__dataHost;\n      /** @type {!Object} */\n      this.__dataTemp;\n      /** @type {boolean} */\n      this.__dataClientsInitialized;\n      /** @type {!Object} */\n      this.__data;\n      /** @type {!Object|null} */\n      this.__dataPending;\n      /** @type {!Object} */\n      this.__dataOld;\n      /** @type {Object} */\n      this.__computeEffects;\n      /** @type {Object} */\n      this.__computeInfo;\n      /** @type {Object} */\n      this.__reflectEffects;\n      /** @type {Object} */\n      this.__notifyEffects;\n      /** @type {Object} */\n      this.__propagateEffects;\n      /** @type {Object} */\n      this.__observeEffects;\n      /** @type {Object} */\n      this.__readOnly;\n      /** @type {!TemplateInfo} */\n      this.__templateInfo;\n      /** @type {boolean} */\n      this._overrideLegacyUndefined;\n    }\n\n    get PROPERTY_EFFECT_TYPES() {\n      return TYPES;\n    }\n\n    /**\n     * @override\n     * @return {void}\n     */\n    _initializeProperties() {\n      super._initializeProperties();\n      this._registerHost();\n      this.__dataClientsReady = false;\n      this.__dataPendingClients = null;\n      this.__dataToNotify = null;\n      this.__dataLinkedPaths = null;\n      this.__dataHasPaths = false;\n      // May be set on instance prior to upgrade\n      this.__dataCompoundStorage = this.__dataCompoundStorage || null;\n      this.__dataHost = this.__dataHost || null;\n      this.__dataTemp = {};\n      this.__dataClientsInitialized = false;\n    }\n\n    _registerHost() {\n      if (hostStack.length) {\n        let host = hostStack[hostStack.length-1];\n        host._enqueueClient(this);\n        // This ensures even non-bound elements have a host set, as\n        // long as they upgrade synchronously\n        this.__dataHost = host;\n      }\n    }\n\n    /**\n     * Overrides `PropertyAccessors` implementation to provide a\n     * more efficient implementation of initializing properties from\n     * the prototype on the instance.\n     *\n     * @override\n     * @param {Object} props Properties to initialize on the prototype\n     * @return {void}\n     */\n    _initializeProtoProperties(props) {\n      this.__data = Object.create(props);\n      this.__dataPending = Object.create(props);\n      this.__dataOld = {};\n    }\n\n    /**\n     * Overrides `PropertyAccessors` implementation to avoid setting\n     * `_setProperty`'s `shouldNotify: true`.\n     *\n     * @override\n     * @param {Object} props Properties to initialize on the instance\n     * @return {void}\n     */\n    _initializeInstanceProperties(props) {\n      let readOnly = this[TYPES.READ_ONLY];\n      for (let prop in props) {\n        if (!readOnly || !readOnly[prop]) {\n          this.__dataPending = this.__dataPending || {};\n          this.__dataOld = this.__dataOld || {};\n          this.__data[prop] = this.__dataPending[prop] = props[prop];\n        }\n      }\n    }\n\n    // Prototype setup ----------------------------------------\n\n    /**\n     * Equivalent to static `addPropertyEffect` API but can be called on\n     * an instance to add effects at runtime.  See that method for\n     * full API docs.\n     *\n     * @override\n     * @param {string} property Property that should trigger the effect\n     * @param {string} type Effect type, from this.PROPERTY_EFFECT_TYPES\n     * @param {Object=} effect Effect metadata object\n     * @return {void}\n     * @protected\n     */\n    _addPropertyEffect(property, type, effect) {\n      this._createPropertyAccessor(property, type == TYPES.READ_ONLY);\n      // effects are accumulated into arrays per property based on type\n      let effects = ensureOwnEffectMap(this, type, true)[property];\n      if (!effects) {\n        effects = this[type][property] = [];\n      }\n      effects.push(effect);\n    }\n\n    /**\n     * Removes the given property effect.\n     *\n     * @override\n     * @param {string} property Property the effect was associated with\n     * @param {string} type Effect type, from this.PROPERTY_EFFECT_TYPES\n     * @param {Object=} effect Effect metadata object to remove\n     * @return {void}\n     */\n    _removePropertyEffect(property, type, effect) {\n      let effects = ensureOwnEffectMap(this, type, true)[property];\n      let idx = effects.indexOf(effect);\n      if (idx >= 0) {\n        effects.splice(idx, 1);\n      }\n    }\n\n    /**\n     * Returns whether the current prototype/instance has a property effect\n     * of a certain type.\n     *\n     * @override\n     * @param {string} property Property name\n     * @param {string=} type Effect type, from this.PROPERTY_EFFECT_TYPES\n     * @return {boolean} True if the prototype/instance has an effect of this\n     *     type\n     * @protected\n     */\n    _hasPropertyEffect(property, type) {\n      let effects = this[type];\n      return Boolean(effects && effects[property]);\n    }\n\n    /**\n     * Returns whether the current prototype/instance has a \"read only\"\n     * accessor for the given property.\n     *\n     * @override\n     * @param {string} property Property name\n     * @return {boolean} True if the prototype/instance has an effect of this\n     *     type\n     * @protected\n     */\n    _hasReadOnlyEffect(property) {\n      return this._hasPropertyEffect(property, TYPES.READ_ONLY);\n    }\n\n    /**\n     * Returns whether the current prototype/instance has a \"notify\"\n     * property effect for the given property.\n     *\n     * @override\n     * @param {string} property Property name\n     * @return {boolean} True if the prototype/instance has an effect of this\n     *     type\n     * @protected\n     */\n    _hasNotifyEffect(property) {\n      return this._hasPropertyEffect(property, TYPES.NOTIFY);\n    }\n\n    /**\n     * Returns whether the current prototype/instance has a \"reflect to\n     * attribute\" property effect for the given property.\n     *\n     * @override\n     * @param {string} property Property name\n     * @return {boolean} True if the prototype/instance has an effect of this\n     *     type\n     * @protected\n     */\n    _hasReflectEffect(property) {\n      return this._hasPropertyEffect(property, TYPES.REFLECT);\n    }\n\n    /**\n     * Returns whether the current prototype/instance has a \"computed\"\n     * property effect for the given property.\n     *\n     * @override\n     * @param {string} property Property name\n     * @return {boolean} True if the prototype/instance has an effect of this\n     *     type\n     * @protected\n     */\n    _hasComputedEffect(property) {\n      return this._hasPropertyEffect(property, TYPES.COMPUTE);\n    }\n\n    // Runtime ----------------------------------------\n\n    /**\n     * Sets a pending property or path.  If the root property of the path in\n     * question had no accessor, the path is set, otherwise it is enqueued\n     * via `_setPendingProperty`.\n     *\n     * This function isolates relatively expensive functionality necessary\n     * for the public API (`set`, `setProperties`, `notifyPath`, and property\n     * change listeners via {{...}} bindings), such that it is only done\n     * when paths enter the system, and not at every propagation step.  It\n     * also sets a `__dataHasPaths` flag on the instance which is used to\n     * fast-path slower path-matching code in the property effects host paths.\n     *\n     * `path` can be a path string or array of path parts as accepted by the\n     * public API.\n     *\n     * @override\n     * @param {string | !Array<number|string>} path Path to set\n     * @param {*} value Value to set\n     * @param {boolean=} shouldNotify Set to true if this change should\n     *  cause a property notification event dispatch\n     * @param {boolean=} isPathNotification If the path being set is a path\n     *   notification of an already changed value, as opposed to a request\n     *   to set and notify the change.  In the latter `false` case, a dirty\n     *   check is performed and then the value is set to the path before\n     *   enqueuing the pending property change.\n     * @return {boolean} Returns true if the property/path was enqueued in\n     *   the pending changes bag.\n     * @protected\n     */\n    _setPendingPropertyOrPath(path, value, shouldNotify, isPathNotification) {\n      if (isPathNotification ||\n          root(Array.isArray(path) ? path[0] : path) !== path) {\n        // Dirty check changes being set to a path against the actual object,\n        // since this is the entry point for paths into the system; from here\n        // the only dirty checks are against the `__dataTemp` cache to prevent\n        // duplicate work in the same turn only. Note, if this was a notification\n        // of a change already set to a path (isPathNotification: true),\n        // we always let the change through and skip the `set` since it was\n        // already dirty checked at the point of entry and the underlying\n        // object has already been updated\n        if (!isPathNotification) {\n          let old = get(this, path);\n          path = /** @type {string} */ (set(this, path, value));\n          // Use property-accessor's simpler dirty check\n          if (!path || !super._shouldPropertyChange(path, value, old)) {\n            return false;\n          }\n        }\n        this.__dataHasPaths = true;\n        if (this._setPendingProperty(/**@type{string}*/(path), value, shouldNotify)) {\n          computeLinkedPaths(this, /**@type{string}*/ (path), value);\n          return true;\n        }\n      } else {\n        if (this.__dataHasAccessor && this.__dataHasAccessor[path]) {\n          return this._setPendingProperty(/**@type{string}*/(path), value, shouldNotify);\n        } else {\n          this[path] = value;\n        }\n      }\n      return false;\n    }\n\n    /**\n     * Applies a value to a non-Polymer element/node's property.\n     *\n     * The implementation makes a best-effort at binding interop:\n     * Some native element properties have side-effects when\n     * re-setting the same value (e.g. setting `<input>.value` resets the\n     * cursor position), so we do a dirty-check before setting the value.\n     * However, for better interop with non-Polymer custom elements that\n     * accept objects, we explicitly re-set object changes coming from the\n     * Polymer world (which may include deep object changes without the\n     * top reference changing), erring on the side of providing more\n     * information.\n     *\n     * Users may override this method to provide alternate approaches.\n     *\n     * @override\n     * @param {!Node} node The node to set a property on\n     * @param {string} prop The property to set\n     * @param {*} value The value to set\n     * @return {void}\n     * @protected\n     */\n    _setUnmanagedPropertyToNode(node, prop, value) {\n      // It is a judgment call that resetting primitives is\n      // \"bad\" and resettings objects is also \"good\"; alternatively we could\n      // implement a whitelist of tag & property values that should never\n      // be reset (e.g. <input>.value && <select>.value)\n      if (value !== node[prop] || typeof value == 'object') {\n        // Note, className needs style scoping so this needs wrapping.\n        if (prop === 'className') {\n          node = /** @type {!Node} */(wrap(node));\n        }\n        node[prop] = value;\n      }\n    }\n\n    /**\n     * Overrides the `PropertiesChanged` implementation to introduce special\n     * dirty check logic depending on the property & value being set:\n     *\n     * 1. Any value set to a path (e.g. 'obj.prop': 42 or 'obj.prop': {...})\n     *    Stored in `__dataTemp`, dirty checked against `__dataTemp`\n     * 2. Object set to simple property (e.g. 'prop': {...})\n     *    Stored in `__dataTemp` and `__data`, dirty checked against\n     *    `__dataTemp` by default implementation of `_shouldPropertyChange`\n     * 3. Primitive value set to simple property (e.g. 'prop': 42)\n     *    Stored in `__data`, dirty checked against `__data`\n     *\n     * The dirty-check is important to prevent cycles due to two-way\n     * notification, but paths and objects are only dirty checked against any\n     * previous value set during this turn via a \"temporary cache\" that is\n     * cleared when the last `_propertiesChanged` exits. This is so:\n     * a. any cached array paths (e.g. 'array.3.prop') may be invalidated\n     *    due to array mutations like shift/unshift/splice; this is fine\n     *    since path changes are dirty-checked at user entry points like `set`\n     * b. dirty-checking for objects only lasts one turn to allow the user\n     *    to mutate the object in-place and re-set it with the same identity\n     *    and have all sub-properties re-propagated in a subsequent turn.\n     *\n     * The temp cache is not necessarily sufficient to prevent invalid array\n     * paths, since a splice can happen during the same turn (with pathological\n     * user code); we could introduce a \"fixup\" for temporarily cached array\n     * paths if needed: https://github.com/Polymer/polymer/issues/4227\n     *\n     * @override\n     * @param {string} property Name of the property\n     * @param {*} value Value to set\n     * @param {boolean=} shouldNotify True if property should fire notification\n     *   event (applies only for `notify: true` properties)\n     * @return {boolean} Returns true if the property changed\n     */\n    _setPendingProperty(property, value, shouldNotify) {\n      let propIsPath = this.__dataHasPaths && isPath(property);\n      let prevProps = propIsPath ? this.__dataTemp : this.__data;\n      if (this._shouldPropertyChange(property, value, prevProps[property])) {\n        if (!this.__dataPending) {\n          this.__dataPending = {};\n          this.__dataOld = {};\n        }\n        // Ensure old is captured from the last turn\n        if (!(property in this.__dataOld)) {\n          this.__dataOld[property] = this.__data[property];\n        }\n        // Paths are stored in temporary cache (cleared at end of turn),\n        // which is used for dirty-checking, all others stored in __data\n        if (propIsPath) {\n          this.__dataTemp[property] = value;\n        } else {\n          this.__data[property] = value;\n        }\n        // All changes go into pending property bag, passed to _propertiesChanged\n        this.__dataPending[property] = value;\n        // Track properties that should notify separately\n        if (propIsPath || (this[TYPES.NOTIFY] && this[TYPES.NOTIFY][property])) {\n          this.__dataToNotify = this.__dataToNotify || {};\n          this.__dataToNotify[property] = shouldNotify;\n        }\n        return true;\n      }\n      return false;\n    }\n\n    /**\n     * Overrides base implementation to ensure all accessors set `shouldNotify`\n     * to true, for per-property notification tracking.\n     *\n     * @override\n     * @param {string} property Name of the property\n     * @param {*} value Value to set\n     * @return {void}\n     */\n    _setProperty(property, value) {\n      if (this._setPendingProperty(property, value, true)) {\n        this._invalidateProperties();\n      }\n    }\n\n    /**\n     * Overrides `PropertyAccessor`'s default async queuing of\n     * `_propertiesChanged`: if `__dataReady` is false (has not yet been\n     * manually flushed), the function no-ops; otherwise flushes\n     * `_propertiesChanged` synchronously.\n     *\n     * @override\n     * @return {void}\n     */\n    _invalidateProperties() {\n      if (this.__dataReady) {\n        this._flushProperties();\n      }\n    }\n\n    /**\n     * Enqueues the given client on a list of pending clients, whose\n     * pending property changes can later be flushed via a call to\n     * `_flushClients`.\n     *\n     * @override\n     * @param {Object} client PropertyEffects client to enqueue\n     * @return {void}\n     * @protected\n     */\n    _enqueueClient(client) {\n      this.__dataPendingClients = this.__dataPendingClients || [];\n      if (client !== this) {\n        this.__dataPendingClients.push(client);\n      }\n    }\n\n    /**\n     * Flushes any clients previously enqueued via `_enqueueClient`, causing\n     * their `_flushProperties` method to run.\n     *\n     * @override\n     * @return {void}\n     * @protected\n     */\n    _flushClients() {\n      if (!this.__dataClientsReady) {\n        this.__dataClientsReady = true;\n        this._readyClients();\n        // Override point where accessors are turned on; importantly,\n        // this is after clients have fully readied, providing a guarantee\n        // that any property effects occur only after all clients are ready.\n        this.__dataReady = true;\n      } else {\n        this.__enableOrFlushClients();\n      }\n    }\n\n    // NOTE: We ensure clients either enable or flush as appropriate. This\n    // handles two corner cases:\n    // (1) clients flush properly when connected/enabled before the host\n    // enables; e.g.\n    //   (a) Templatize stamps with no properties and does not flush and\n    //   (b) the instance is inserted into dom and\n    //   (c) then the instance flushes.\n    // (2) clients enable properly when not connected/enabled when the host\n    // flushes; e.g.\n    //   (a) a template is runtime stamped and not yet connected/enabled\n    //   (b) a host sets a property, causing stamped dom to flush\n    //   (c) the stamped dom enables.\n    __enableOrFlushClients() {\n      let clients = this.__dataPendingClients;\n      if (clients) {\n        this.__dataPendingClients = null;\n        for (let i=0; i < clients.length; i++) {\n          let client = clients[i];\n          if (!client.__dataEnabled) {\n            client._enableProperties();\n          } else if (client.__dataPending) {\n            client._flushProperties();\n          }\n        }\n      }\n    }\n\n    /**\n     * Perform any initial setup on client dom. Called before the first\n     * `_flushProperties` call on client dom and before any element\n     * observers are called.\n     *\n     * @override\n     * @return {void}\n     * @protected\n     */\n    _readyClients() {\n      this.__enableOrFlushClients();\n    }\n\n    /**\n     * Sets a bag of property changes to this instance, and\n     * synchronously processes all effects of the properties as a batch.\n     *\n     * Property names must be simple properties, not paths.  Batched\n     * path propagation is not supported.\n     *\n     * @override\n     * @param {Object} props Bag of one or more key-value pairs whose key is\n     *   a property and value is the new value to set for that property.\n     * @param {boolean=} setReadOnly When true, any private values set in\n     *   `props` will be set. By default, `setProperties` will not set\n     *   `readOnly: true` root properties.\n     * @return {void}\n     * @public\n     */\n    setProperties(props, setReadOnly) {\n      for (let path in props) {\n        if (setReadOnly || !this[TYPES.READ_ONLY] || !this[TYPES.READ_ONLY][path]) {\n          //TODO(kschaaf): explicitly disallow paths in setProperty?\n          // wildcard observers currently only pass the first changed path\n          // in the `info` object, and you could do some odd things batching\n          // paths, e.g. {'foo.bar': {...}, 'foo': null}\n          this._setPendingPropertyOrPath(path, props[path], true);\n        }\n      }\n      this._invalidateProperties();\n    }\n\n    /**\n     * Overrides `PropertyAccessors` so that property accessor\n     * side effects are not enabled until after client dom is fully ready.\n     * Also calls `_flushClients` callback to ensure client dom is enabled\n     * that was not enabled as a result of flushing properties.\n     *\n     * @override\n     * @return {void}\n     */\n    ready() {\n      // It is important that `super.ready()` is not called here as it\n      // immediately turns on accessors. Instead, we wait until `readyClients`\n      // to enable accessors to provide a guarantee that clients are ready\n      // before processing any accessors side effects.\n      this._flushProperties();\n      // If no data was pending, `_flushProperties` will not `flushClients`\n      // so ensure this is done.\n      if (!this.__dataClientsReady) {\n        this._flushClients();\n      }\n      // Before ready, client notifications do not trigger _flushProperties.\n      // Therefore a flush is necessary here if data has been set.\n      if (this.__dataPending) {\n        this._flushProperties();\n      }\n    }\n\n    /**\n     * Implements `PropertyAccessors`'s properties changed callback.\n     *\n     * Runs each class of effects for the batch of changed properties in\n     * a specific order (compute, propagate, reflect, observe, notify).\n     *\n     * @override\n     * @param {!Object} currentProps Bag of all current accessor values\n     * @param {?Object} changedProps Bag of properties changed since the last\n     *   call to `_propertiesChanged`\n     * @param {?Object} oldProps Bag of previous values for each property\n     *   in `changedProps`\n     * @return {void}\n     */\n    _propertiesChanged(currentProps, changedProps, oldProps) {\n      // ----------------------------\n      // let c = Object.getOwnPropertyNames(changedProps || {});\n      // window.debug && console.group(this.localName + '#' + this.id + ': ' + c);\n      // if (window.debug) { debugger; }\n      // ----------------------------\n      let hasPaths = this.__dataHasPaths;\n      this.__dataHasPaths = false;\n      let notifyProps;\n      // Compute properties\n      runComputedEffects(this, changedProps, oldProps, hasPaths);\n      // Clear notify properties prior to possible reentry (propagate, observe),\n      // but after computing effects have a chance to add to them\n      notifyProps = this.__dataToNotify;\n      this.__dataToNotify = null;\n      // Propagate properties to clients\n      this._propagatePropertyChanges(changedProps, oldProps, hasPaths);\n      // Flush clients\n      this._flushClients();\n      // Reflect properties\n      runEffects(this, this[TYPES.REFLECT], changedProps, oldProps, hasPaths);\n      // Observe properties\n      runEffects(this, this[TYPES.OBSERVE], changedProps, oldProps, hasPaths);\n      // Notify properties to host\n      if (notifyProps) {\n        runNotifyEffects(this, notifyProps, changedProps, oldProps, hasPaths);\n      }\n      // Clear temporary cache at end of turn\n      if (this.__dataCounter == 1) {\n        this.__dataTemp = {};\n      }\n      // ----------------------------\n      // window.debug && console.groupEnd(this.localName + '#' + this.id + ': ' + c);\n      // ----------------------------\n    }\n\n    /**\n     * Called to propagate any property changes to stamped template nodes\n     * managed by this element.\n     *\n     * @override\n     * @param {Object} changedProps Bag of changed properties\n     * @param {Object} oldProps Bag of previous values for changed properties\n     * @param {boolean} hasPaths True with `props` contains one or more paths\n     * @return {void}\n     * @protected\n     */\n    _propagatePropertyChanges(changedProps, oldProps, hasPaths) {\n      if (this[TYPES.PROPAGATE]) {\n        runEffects(this, this[TYPES.PROPAGATE], changedProps, oldProps, hasPaths);\n      }\n      if (this.__templateInfo) {\n        this._runEffectsForTemplate(this.__templateInfo, changedProps, oldProps, hasPaths);\n      }\n    }\n\n    _runEffectsForTemplate(templateInfo, changedProps, oldProps, hasPaths) {\n      const baseRunEffects = (changedProps, hasPaths) => {\n        runEffects(this, templateInfo.propertyEffects, changedProps, oldProps,\n          hasPaths, templateInfo.nodeList);\n        for (let info=templateInfo.firstChild; info; info=info.nextSibling) {\n          this._runEffectsForTemplate(info, changedProps, oldProps, hasPaths);\n        }\n      };\n      if (templateInfo.runEffects) {\n        templateInfo.runEffects(baseRunEffects, changedProps, hasPaths);\n      } else {\n        baseRunEffects(changedProps, hasPaths);\n      }\n    }\n\n    /**\n     * Aliases one data path as another, such that path notifications from one\n     * are routed to the other.\n     *\n     * @override\n     * @param {string | !Array<string|number>} to Target path to link.\n     * @param {string | !Array<string|number>} from Source path to link.\n     * @return {void}\n     * @public\n     */\n    linkPaths(to, from) {\n      to = normalize(to);\n      from = normalize(from);\n      this.__dataLinkedPaths = this.__dataLinkedPaths || {};\n      this.__dataLinkedPaths[to] = from;\n    }\n\n    /**\n     * Removes a data path alias previously established with `_linkPaths`.\n     *\n     * Note, the path to unlink should be the target (`to`) used when\n     * linking the paths.\n     *\n     * @override\n     * @param {string | !Array<string|number>} path Target path to unlink.\n     * @return {void}\n     * @public\n     */\n    unlinkPaths(path) {\n      path = normalize(path);\n      if (this.__dataLinkedPaths) {\n        delete this.__dataLinkedPaths[path];\n      }\n    }\n\n    /**\n     * Notify that an array has changed.\n     *\n     * Example:\n     *\n     *     this.items = [ {name: 'Jim'}, {name: 'Todd'}, {name: 'Bill'} ];\n     *     ...\n     *     this.items.splice(1, 1, {name: 'Sam'});\n     *     this.items.push({name: 'Bob'});\n     *     this.notifySplices('items', [\n     *       { index: 1, removed: [{name: 'Todd'}], addedCount: 1,\n     *         object: this.items, type: 'splice' },\n     *       { index: 3, removed: [], addedCount: 1,\n     *         object: this.items, type: 'splice'}\n     *     ]);\n     *\n     * @param {string} path Path that should be notified.\n     * @param {Array} splices Array of splice records indicating ordered\n     *   changes that occurred to the array. Each record should have the\n     *   following fields:\n     *    * index: index at which the change occurred\n     *    * removed: array of items that were removed from this index\n     *    * addedCount: number of new items added at this index\n     *    * object: a reference to the array in question\n     *    * type: the string literal 'splice'\n     *\n     *   Note that splice records _must_ be normalized such that they are\n     *   reported in index order (raw results from `Object.observe` are not\n     *   ordered and must be normalized/merged before notifying).\n     *\n     * @override\n     * @return {void}\n     * @public\n     */\n    notifySplices(path, splices) {\n      let info = {path: ''};\n      let array = /** @type {Array} */(get(this, path, info));\n      notifySplices(this, array, info.path, splices);\n    }\n\n    /**\n     * Convenience method for reading a value from a path.\n     *\n     * Note, if any part in the path is undefined, this method returns\n     * `undefined` (this method does not throw when dereferencing undefined\n     * paths).\n     *\n     * @override\n     * @param {(string|!Array<(string|number)>)} path Path to the value\n     *   to read.  The path may be specified as a string (e.g. `foo.bar.baz`)\n     *   or an array of path parts (e.g. `['foo.bar', 'baz']`).  Note that\n     *   bracketed expressions are not supported; string-based path parts\n     *   *must* be separated by dots.  Note that when dereferencing array\n     *   indices, the index may be used as a dotted part directly\n     *   (e.g. `users.12.name` or `['users', 12, 'name']`).\n     * @param {Object=} root Root object from which the path is evaluated.\n     * @return {*} Value at the path, or `undefined` if any part of the path\n     *   is undefined.\n     * @public\n     */\n    get(path, root) {\n      return get(root || this, path);\n    }\n\n    /**\n     * Convenience method for setting a value to a path and notifying any\n     * elements bound to the same path.\n     *\n     * Note, if any part in the path except for the last is undefined,\n     * this method does nothing (this method does not throw when\n     * dereferencing undefined paths).\n     *\n     * @override\n     * @param {(string|!Array<(string|number)>)} path Path to the value\n     *   to write.  The path may be specified as a string (e.g. `'foo.bar.baz'`)\n     *   or an array of path parts (e.g. `['foo.bar', 'baz']`).  Note that\n     *   bracketed expressions are not supported; string-based path parts\n     *   *must* be separated by dots.  Note that when dereferencing array\n     *   indices, the index may be used as a dotted part directly\n     *   (e.g. `'users.12.name'` or `['users', 12, 'name']`).\n     * @param {*} value Value to set at the specified path.\n     * @param {Object=} root Root object from which the path is evaluated.\n     *   When specified, no notification will occur.\n     * @return {void}\n     * @public\n     */\n    set(path, value, root) {\n      if (root) {\n        set(root, path, value);\n      } else {\n        if (!this[TYPES.READ_ONLY] || !this[TYPES.READ_ONLY][/** @type {string} */(path)]) {\n          if (this._setPendingPropertyOrPath(path, value, true)) {\n            this._invalidateProperties();\n          }\n        }\n      }\n    }\n\n    /**\n     * Adds items onto the end of the array at the path specified.\n     *\n     * The arguments after `path` and return value match that of\n     * `Array.prototype.push`.\n     *\n     * This method notifies other paths to the same array that a\n     * splice occurred to the array.\n     *\n     * @override\n     * @param {string | !Array<string|number>} path Path to array.\n     * @param {...*} items Items to push onto array\n     * @return {number} New length of the array.\n     * @public\n     */\n    push(path, ...items) {\n      let info = {path: ''};\n      let array = /** @type {Array}*/(get(this, path, info));\n      let len = array.length;\n      let ret = array.push(...items);\n      if (items.length) {\n        notifySplice(this, array, info.path, len, items.length, []);\n      }\n      return ret;\n    }\n\n    /**\n     * Removes an item from the end of array at the path specified.\n     *\n     * The arguments after `path` and return value match that of\n     * `Array.prototype.pop`.\n     *\n     * This method notifies other paths to the same array that a\n     * splice occurred to the array.\n     *\n     * @override\n     * @param {string | !Array<string|number>} path Path to array.\n     * @return {*} Item that was removed.\n     * @public\n     */\n    pop(path) {\n      let info = {path: ''};\n      let array = /** @type {Array} */(get(this, path, info));\n      let hadLength = Boolean(array.length);\n      let ret = array.pop();\n      if (hadLength) {\n        notifySplice(this, array, info.path, array.length, 0, [ret]);\n      }\n      return ret;\n    }\n\n    /**\n     * Starting from the start index specified, removes 0 or more items\n     * from the array and inserts 0 or more new items in their place.\n     *\n     * The arguments after `path` and return value match that of\n     * `Array.prototype.splice`.\n     *\n     * This method notifies other paths to the same array that a\n     * splice occurred to the array.\n     *\n     * @override\n     * @param {string | !Array<string|number>} path Path to array.\n     * @param {number} start Index from which to start removing/inserting.\n     * @param {number=} deleteCount Number of items to remove.\n     * @param {...*} items Items to insert into array.\n     * @return {!Array} Array of removed items.\n     * @public\n     */\n    splice(path, start, deleteCount, ...items) {\n      let info = {path : ''};\n      let array = /** @type {Array} */(get(this, path, info));\n      // Normalize fancy native splice handling of crazy start values\n      if (start < 0) {\n        start = array.length - Math.floor(-start);\n      } else if (start) {\n        start = Math.floor(start);\n      }\n      // array.splice does different things based on the number of arguments\n      // you pass in. Therefore, array.splice(0) and array.splice(0, undefined)\n      // do different things. In the former, the whole array is cleared. In the\n      // latter, no items are removed.\n      // This means that we need to detect whether 1. one of the arguments\n      // is actually passed in and then 2. determine how many arguments\n      // we should pass on to the native array.splice\n      //\n      let ret;\n      // Omit any additional arguments if they were not passed in\n      if (arguments.length === 2) {\n        ret = array.splice(start);\n      // Either start was undefined and the others were defined, but in this\n      // case we can safely pass on all arguments\n      //\n      // Note: this includes the case where none of the arguments were passed in,\n      // e.g. this.splice('array'). However, if both start and deleteCount\n      // are undefined, array.splice will not modify the array (as expected)\n      } else {\n        ret = array.splice(start, deleteCount, ...items);\n      }\n      // At the end, check whether any items were passed in (e.g. insertions)\n      // or if the return array contains items (e.g. deletions).\n      // Only notify if items were added or deleted.\n      if (items.length || ret.length) {\n        notifySplice(this, array, info.path, start, items.length, ret);\n      }\n      return ret;\n    }\n\n    /**\n     * Removes an item from the beginning of array at the path specified.\n     *\n     * The arguments after `path` and return value match that of\n     * `Array.prototype.pop`.\n     *\n     * This method notifies other paths to the same array that a\n     * splice occurred to the array.\n     *\n     * @override\n     * @param {string | !Array<string|number>} path Path to array.\n     * @return {*} Item that was removed.\n     * @public\n     */\n    shift(path) {\n      let info = {path: ''};\n      let array = /** @type {Array} */(get(this, path, info));\n      let hadLength = Boolean(array.length);\n      let ret = array.shift();\n      if (hadLength) {\n        notifySplice(this, array, info.path, 0, 0, [ret]);\n      }\n      return ret;\n    }\n\n    /**\n     * Adds items onto the beginning of the array at the path specified.\n     *\n     * The arguments after `path` and return value match that of\n     * `Array.prototype.push`.\n     *\n     * This method notifies other paths to the same array that a\n     * splice occurred to the array.\n     *\n     * @override\n     * @param {string | !Array<string|number>} path Path to array.\n     * @param {...*} items Items to insert info array\n     * @return {number} New length of the array.\n     * @public\n     */\n    unshift(path, ...items) {\n      let info = {path: ''};\n      let array = /** @type {Array} */(get(this, path, info));\n      let ret = array.unshift(...items);\n      if (items.length) {\n        notifySplice(this, array, info.path, 0, items.length, []);\n      }\n      return ret;\n    }\n\n    /**\n     * Notify that a path has changed.\n     *\n     * Example:\n     *\n     *     this.item.user.name = 'Bob';\n     *     this.notifyPath('item.user.name');\n     *\n     * @override\n     * @param {string} path Path that should be notified.\n     * @param {*=} value Value at the path (optional).\n     * @return {void}\n     * @public\n     */\n    notifyPath(path, value) {\n      /** @type {string} */\n      let propPath;\n      if (arguments.length == 1) {\n        // Get value if not supplied\n        let info = {path: ''};\n        value = get(this, path, info);\n        propPath = info.path;\n      } else if (Array.isArray(path)) {\n        // Normalize path if needed\n        propPath = normalize(path);\n      } else {\n        propPath = /** @type{string} */(path);\n      }\n      if (this._setPendingPropertyOrPath(propPath, value, true, true)) {\n        this._invalidateProperties();\n      }\n    }\n\n    /**\n     * Equivalent to static `createReadOnlyProperty` API but can be called on\n     * an instance to add effects at runtime.  See that method for\n     * full API docs.\n     *\n     * @override\n     * @param {string} property Property name\n     * @param {boolean=} protectedSetter Creates a custom protected setter\n     *   when `true`.\n     * @return {void}\n     * @protected\n     */\n    _createReadOnlyProperty(property, protectedSetter) {\n      this._addPropertyEffect(property, TYPES.READ_ONLY);\n      if (protectedSetter) {\n        this['_set' + upper(property)] = /** @this {PropertyEffects} */function(value) {\n          this._setProperty(property, value);\n        };\n      }\n    }\n\n    /**\n     * Equivalent to static `createPropertyObserver` API but can be called on\n     * an instance to add effects at runtime.  See that method for\n     * full API docs.\n     *\n     * @override\n     * @param {string} property Property name\n     * @param {string|function(*,*)} method Function or name of observer method\n     *     to call\n     * @param {boolean=} dynamicFn Whether the method name should be included as\n     *   a dependency to the effect.\n     * @return {void}\n     * @protected\n     */\n    _createPropertyObserver(property, method, dynamicFn) {\n      let info = { property, method, dynamicFn: Boolean(dynamicFn) };\n      this._addPropertyEffect(property, TYPES.OBSERVE, {\n        fn: runObserverEffect, info, trigger: {name: property}\n      });\n      if (dynamicFn) {\n        this._addPropertyEffect(/** @type {string} */(method), TYPES.OBSERVE, {\n          fn: runObserverEffect, info, trigger: {name: method}\n        });\n      }\n    }\n\n    /**\n     * Equivalent to static `createMethodObserver` API but can be called on\n     * an instance to add effects at runtime.  See that method for\n     * full API docs.\n     *\n     * @override\n     * @param {string} expression Method expression\n     * @param {boolean|Object=} dynamicFn Boolean or object map indicating\n     *   whether method names should be included as a dependency to the effect.\n     * @return {void}\n     * @protected\n     */\n    _createMethodObserver(expression, dynamicFn) {\n      let sig = parseMethod(expression);\n      if (!sig) {\n        throw new Error(\"Malformed observer expression '\" + expression + \"'\");\n      }\n      createMethodEffect(this, sig, TYPES.OBSERVE, runMethodEffect, null, dynamicFn);\n    }\n\n    /**\n     * Equivalent to static `createNotifyingProperty` API but can be called on\n     * an instance to add effects at runtime.  See that method for\n     * full API docs.\n     *\n     * @override\n     * @param {string} property Property name\n     * @return {void}\n     * @protected\n     */\n    _createNotifyingProperty(property) {\n      this._addPropertyEffect(property, TYPES.NOTIFY, {\n        fn: runNotifyEffect,\n        info: {\n          eventName: camelToDashCase(property) + '-changed',\n          property: property\n        }\n      });\n    }\n\n    /**\n     * Equivalent to static `createReflectedProperty` API but can be called on\n     * an instance to add effects at runtime.  See that method for\n     * full API docs.\n     *\n     * @override\n     * @param {string} property Property name\n     * @return {void}\n     * @protected\n     * @suppress {missingProperties} go/missingfnprops\n     */\n    _createReflectedProperty(property) {\n      let attr = this.constructor.attributeNameForProperty(property);\n      if (attr[0] === '-') {\n        console.warn('Property ' + property + ' cannot be reflected to attribute ' +\n          attr + ' because \"-\" is not a valid starting attribute name. Use a lowercase first letter for the property instead.');\n      } else {\n        this._addPropertyEffect(property, TYPES.REFLECT, {\n          fn: runReflectEffect,\n          info: {\n            attrName: attr\n          }\n        });\n      }\n    }\n\n    /**\n     * Equivalent to static `createComputedProperty` API but can be called on\n     * an instance to add effects at runtime.  See that method for\n     * full API docs.\n     *\n     * @override\n     * @param {string} property Name of computed property to set\n     * @param {string} expression Method expression\n     * @param {boolean|Object=} dynamicFn Boolean or object map indicating\n     *   whether method names should be included as a dependency to the effect.\n     * @return {void}\n     * @protected\n     */\n    _createComputedProperty(property, expression, dynamicFn) {\n      let sig = parseMethod(expression);\n      if (!sig) {\n        throw new Error(\"Malformed computed expression '\" + expression + \"'\");\n      }\n      const info = createMethodEffect(this, sig, TYPES.COMPUTE, runComputedEffect, property, dynamicFn);\n      // Effects are normally stored as map of dependency->effect, but for\n      // ordered computation, we also need tree of computedProp->dependencies\n      ensureOwnEffectMap(this, COMPUTE_INFO)[property] = info;\n    }\n\n    /**\n     * Gather the argument values for a method specified in the provided array\n     * of argument metadata.\n     *\n     * The `path` and `value` arguments are used to fill in wildcard descriptor\n     * when the method is being called as a result of a path notification.\n     *\n     * @param {!Array<!MethodArg>} args Array of argument metadata\n     * @param {string} path Property/path name that triggered the method effect\n     * @param {Object} props Bag of current property changes\n     * @return {!Array<*>} Array of argument values\n     * @private\n     */\n    _marshalArgs(args, path, props) {\n      const data = this.__data;\n      const values = [];\n      for (let i=0, l=args.length; i<l; i++) {\n        let {name, structured, wildcard, value, literal} = args[i];\n        if (!literal) {\n          if (wildcard) {\n            const matches = isDescendant(name, path);\n            const pathValue = getArgValue(data, props, matches ? path : name);\n            value = {\n              path: matches ? path : name,\n              value: pathValue,\n              base: matches ? get(data, name) : pathValue\n            };\n          } else {\n            value = structured ? getArgValue(data, props, name) : data[name];\n          }\n        }\n        // When the `legacyUndefined` flag is enabled, pass a no-op value\n        // so that the observer, computed property, or compound binding is aborted.\n        if (legacyUndefined && !this._overrideLegacyUndefined && value === undefined && args.length > 1) {\n          return NOOP;\n        }\n        values[i] = value;\n      }\n      return values;\n    }\n\n    // -- static class methods ------------\n\n    /**\n     * Ensures an accessor exists for the specified property, and adds\n     * to a list of \"property effects\" that will run when the accessor for\n     * the specified property is set.  Effects are grouped by \"type\", which\n     * roughly corresponds to a phase in effect processing.  The effect\n     * metadata should be in the following form:\n     *\n     *     {\n     *       fn: effectFunction, // Reference to function to call to perform effect\n     *       info: { ... }       // Effect metadata passed to function\n     *       trigger: {          // Optional triggering metadata; if not provided\n     *         name: string      // the property is treated as a wildcard\n     *         structured: boolean\n     *         wildcard: boolean\n     *       }\n     *     }\n     *\n     * Effects are called from `_propertiesChanged` in the following order by\n     * type:\n     *\n     * 1. COMPUTE\n     * 2. PROPAGATE\n     * 3. REFLECT\n     * 4. OBSERVE\n     * 5. NOTIFY\n     *\n     * Effect functions are called with the following signature:\n     *\n     *     effectFunction(inst, path, props, oldProps, info, hasPaths)\n     *\n     * @param {string} property Property that should trigger the effect\n     * @param {string} type Effect type, from this.PROPERTY_EFFECT_TYPES\n     * @param {Object=} effect Effect metadata object\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static addPropertyEffect(property, type, effect) {\n      this.prototype._addPropertyEffect(property, type, effect);\n    }\n\n    /**\n     * Creates a single-property observer for the given property.\n     *\n     * @param {string} property Property name\n     * @param {string|function(*,*)} method Function or name of observer method to call\n     * @param {boolean=} dynamicFn Whether the method name should be included as\n     *   a dependency to the effect.\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static createPropertyObserver(property, method, dynamicFn) {\n      this.prototype._createPropertyObserver(property, method, dynamicFn);\n    }\n\n    /**\n     * Creates a multi-property \"method observer\" based on the provided\n     * expression, which should be a string in the form of a normal JavaScript\n     * function signature: `'methodName(arg1, [..., argn])'`.  Each argument\n     * should correspond to a property or path in the context of this\n     * prototype (or instance), or may be a literal string or number.\n     *\n     * @param {string} expression Method expression\n     * @param {boolean|Object=} dynamicFn Boolean or object map indicating\n     * @return {void}\n     *   whether method names should be included as a dependency to the effect.\n     * @protected\n     * @nocollapse\n     */\n    static createMethodObserver(expression, dynamicFn) {\n      this.prototype._createMethodObserver(expression, dynamicFn);\n    }\n\n    /**\n     * Causes the setter for the given property to dispatch `<property>-changed`\n     * events to notify of changes to the property.\n     *\n     * @param {string} property Property name\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static createNotifyingProperty(property) {\n      this.prototype._createNotifyingProperty(property);\n    }\n\n    /**\n     * Creates a read-only accessor for the given property.\n     *\n     * To set the property, use the protected `_setProperty` API.\n     * To create a custom protected setter (e.g. `_setMyProp()` for\n     * property `myProp`), pass `true` for `protectedSetter`.\n     *\n     * Note, if the property will have other property effects, this method\n     * should be called first, before adding other effects.\n     *\n     * @param {string} property Property name\n     * @param {boolean=} protectedSetter Creates a custom protected setter\n     *   when `true`.\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static createReadOnlyProperty(property, protectedSetter) {\n      this.prototype._createReadOnlyProperty(property, protectedSetter);\n    }\n\n    /**\n     * Causes the setter for the given property to reflect the property value\n     * to a (dash-cased) attribute of the same name.\n     *\n     * @param {string} property Property name\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static createReflectedProperty(property) {\n      this.prototype._createReflectedProperty(property);\n    }\n\n    /**\n     * Creates a computed property whose value is set to the result of the\n     * method described by the given `expression` each time one or more\n     * arguments to the method changes.  The expression should be a string\n     * in the form of a normal JavaScript function signature:\n     * `'methodName(arg1, [..., argn])'`\n     *\n     * @param {string} property Name of computed property to set\n     * @param {string} expression Method expression\n     * @param {boolean|Object=} dynamicFn Boolean or object map indicating whether\n     *   method names should be included as a dependency to the effect.\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static createComputedProperty(property, expression, dynamicFn) {\n      this.prototype._createComputedProperty(property, expression, dynamicFn);\n    }\n\n    /**\n     * Parses the provided template to ensure binding effects are created\n     * for them, and then ensures property accessors are created for any\n     * dependent properties in the template.  Binding effects for bound\n     * templates are stored in a linked list on the instance so that\n     * templates can be efficiently stamped and unstamped.\n     *\n     * @param {!HTMLTemplateElement} template Template containing binding\n     *   bindings\n     * @return {!TemplateInfo} Template metadata object\n     * @protected\n     * @nocollapse\n     */\n    static bindTemplate(template) {\n      return this.prototype._bindTemplate(template);\n    }\n\n    // -- binding ----------------------------------------------\n\n    /*\n     * Overview of binding flow:\n     *\n     * During finalization (`instanceBinding==false`, `wasPreBound==false`):\n     *  `_bindTemplate(t, false)` called directly during finalization - parses\n     *  the template (for the first time), and then assigns that _prototypical_\n     *  template info to `__preboundTemplateInfo` _on the prototype_; note in\n     *  this case `wasPreBound` is false; this is the first time we're binding\n     *  it, thus we create accessors.\n     *\n     * During first stamping (`instanceBinding==true`, `wasPreBound==true`):\n     *   `_stampTemplate` calls `_bindTemplate(t, true)`: the `templateInfo`\n     *   returned matches the prebound one, and so this is `wasPreBound == true`\n     *   state; thus we _skip_ creating accessors, but _do_ create an instance\n     *   of the template info to serve as the start of our linked list (needs to\n     *   be an instance, not the prototypical one, so that we can add `nodeList`\n     *   to it to contain the `nodeInfo`-ordered list of instance nodes for\n     *   bindings, and so we can chain runtime-stamped template infos off of\n     *   it). At this point, the call to `_stampTemplate` calls\n     *   `applyTemplateInfo` for each nested `<template>` found during parsing\n     *   to hand prototypical `_templateInfo` to them; we also pass the _parent_\n     *   `templateInfo` to the `<template>` so that we have the instance-time\n     *   parent to link the `templateInfo` under in the case it was\n     *   runtime-stamped.\n     *\n     * During subsequent runtime stamping (`instanceBinding==true`,\n     *   `wasPreBound==false`): `_stampTemplate` calls `_bindTemplate(t, true)`\n     *   - here `templateInfo` is guaranteed to _not_ match the prebound one,\n     *   because it was either a different template altogether, or even if it\n     *   was the same template, the step above created a instance of the info;\n     *   in this case `wasPreBound == false`, so we _do_ create accessors, _and_\n     *   link a instance into the linked list.\n     */\n\n    /**\n     * Equivalent to static `bindTemplate` API but can be called on an instance\n     * to add effects at runtime.  See that method for full API docs.\n     *\n     * This method may be called on the prototype (for prototypical template\n     * binding, to avoid creating accessors every instance) once per prototype,\n     * and will be called with `runtimeBinding: true` by `_stampTemplate` to\n     * create and link an instance of the template metadata associated with a\n     * particular stamping.\n     *\n     * @override\n     * @param {!HTMLTemplateElement} template Template containing binding\n     * bindings\n     * @param {boolean=} instanceBinding When false (default), performs\n     * \"prototypical\" binding of the template and overwrites any previously\n     * bound template for the class. When true (as passed from\n     * `_stampTemplate`), the template info is instanced and linked into the\n     * list of bound templates.\n     * @return {!TemplateInfo} Template metadata object; for `runtimeBinding`,\n     * this is an instance of the prototypical template info\n     * @protected\n     * @suppress {missingProperties} go/missingfnprops\n     */\n    _bindTemplate(template, instanceBinding) {\n      let templateInfo = this.constructor._parseTemplate(template);\n      let wasPreBound = this.__preBoundTemplateInfo == templateInfo;\n      // Optimization: since this is called twice for proto-bound templates,\n      // don't attempt to recreate accessors if this template was pre-bound\n      if (!wasPreBound) {\n        for (let prop in templateInfo.propertyEffects) {\n          this._createPropertyAccessor(prop);\n        }\n      }\n      if (instanceBinding) {\n        // For instance-time binding, create instance of template metadata\n        // and link into tree of templates if necessary\n        templateInfo = /** @type {!TemplateInfo} */(Object.create(templateInfo));\n        templateInfo.wasPreBound = wasPreBound;\n        if (!this.__templateInfo) {\n          // Set the info to the root of the tree\n          this.__templateInfo = templateInfo;\n        } else {\n          // Append this template info onto the end of its parent template's\n          // list, which will determine the tree structure via which property\n          // effects are run; if this template was not nested in another\n          // template, use the root template (the first stamped one) as the\n          // parent. Note, `parent` is the `templateInfo` instance for this\n          // template's parent (containing) template, which was set up in\n          // `applyTemplateInfo`.  While a given template's `parent` is set\n          // apriori, it is only added to the parent's child list at the point\n          // that it is being bound, since a template may or may not ever be\n          // stamped, and may be stamped more than once (in which case instances\n          // of the template info will be in the tree under its parent more than\n          // once).\n          const parent = template._parentTemplateInfo || this.__templateInfo;\n          const previous = parent.lastChild;\n          templateInfo.parent = parent;\n          parent.lastChild = templateInfo;\n          templateInfo.previousSibling = previous;\n          if (previous) {\n            previous.nextSibling = templateInfo;\n          } else {\n            parent.firstChild = templateInfo;\n          }\n        }\n      } else {\n        this.__preBoundTemplateInfo = templateInfo;\n      }\n      return templateInfo;\n    }\n\n    /**\n     * Adds a property effect to the given template metadata, which is run\n     * at the \"propagate\" stage of `_propertiesChanged` when the template\n     * has been bound to the element via `_bindTemplate`.\n     *\n     * The `effect` object should match the format in `_addPropertyEffect`.\n     *\n     * @param {Object} templateInfo Template metadata to add effect to\n     * @param {string} prop Property that should trigger the effect\n     * @param {Object=} effect Effect metadata object\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static _addTemplatePropertyEffect(templateInfo, prop, effect) {\n      let hostProps = templateInfo.hostProps = templateInfo.hostProps || {};\n      hostProps[prop] = true;\n      let effects = templateInfo.propertyEffects = templateInfo.propertyEffects || {};\n      let propEffects = effects[prop] = effects[prop] || [];\n      propEffects.push(effect);\n    }\n\n    /**\n     * Stamps the provided template and performs instance-time setup for\n     * Polymer template features, including data bindings, declarative event\n     * listeners, and the `this.$` map of `id`'s to nodes.  A document fragment\n     * is returned containing the stamped DOM, ready for insertion into the\n     * DOM.\n     *\n     * This method may be called more than once; however note that due to\n     * `shadycss` polyfill limitations, only styles from templates prepared\n     * using `ShadyCSS.prepareTemplate` will be correctly polyfilled (scoped\n     * to the shadow root and support CSS custom properties), and note that\n     * `ShadyCSS.prepareTemplate` may only be called once per element. As such,\n     * any styles required by in runtime-stamped templates must be included\n     * in the main element template.\n     *\n     * @param {!HTMLTemplateElement} template Template to stamp\n     * @param {TemplateInfo=} templateInfo Optional bound template info associated\n     *   with the template to be stamped; if omitted the template will be\n     *   automatically bound.\n     * @return {!StampedTemplate} Cloned template content\n     * @override\n     * @protected\n     */\n    _stampTemplate(template, templateInfo) {\n      templateInfo =  templateInfo || /** @type {!TemplateInfo} */(this._bindTemplate(template, true));\n      // Ensures that created dom is `_enqueueClient`'d to this element so\n      // that it can be flushed on next call to `_flushProperties`\n      hostStack.push(this);\n      let dom = super._stampTemplate(template, templateInfo);\n      hostStack.pop();\n      // Add template-instance-specific data to instanced templateInfo\n      templateInfo.nodeList = dom.nodeList;\n      // Capture child nodes to allow unstamping of non-prototypical templates\n      if (!templateInfo.wasPreBound) {\n        let nodes = templateInfo.childNodes = [];\n        for (let n=dom.firstChild; n; n=n.nextSibling) {\n          nodes.push(n);\n        }\n      }\n      dom.templateInfo = templateInfo;\n      // Setup compound storage, 2-way listeners, and dataHost for bindings\n      setupBindings(this, templateInfo);\n      // Flush properties into template nodes; the check on `__dataClientsReady`\n      // ensures we don't needlessly run effects for an element's initial\n      // prototypical template stamping since they will happen as a part of the\n      // first call to `_propertiesChanged`. This flag is set to true\n      // after running the initial propagate effects, and immediately before\n      // flushing clients. Since downstream clients could cause stamping on\n      // this host (e.g. a fastDomIf `dom-if` being forced to render\n      // synchronously), this flag ensures effects for runtime-stamped templates\n      // are run at this point during the initial element boot-up.\n      if (this.__dataClientsReady) {\n        this._runEffectsForTemplate(templateInfo, this.__data, null, false);\n        this._flushClients();\n      }\n      return dom;\n    }\n\n    /**\n     * Removes and unbinds the nodes previously contained in the provided\n     * DocumentFragment returned from `_stampTemplate`.\n     *\n     * @override\n     * @param {!StampedTemplate} dom DocumentFragment previously returned\n     *   from `_stampTemplate` associated with the nodes to be removed\n     * @return {void}\n     * @protected\n     */\n    _removeBoundDom(dom) {\n      // Unlink template info; Note that while the child is unlinked from its\n      // parent list, a template's `parent` reference is never removed, since\n      // this is is determined by the tree structure and applied at\n      // `applyTemplateInfo` time.\n      const templateInfo = dom.templateInfo;\n      const {previousSibling, nextSibling, parent} = templateInfo;\n      if (previousSibling) {\n        previousSibling.nextSibling = nextSibling;\n      } else if (parent) {\n        parent.firstChild = nextSibling;\n      }\n      if (nextSibling) {\n        nextSibling.previousSibling = previousSibling;\n      } else if (parent) {\n        parent.lastChild = previousSibling;\n      }\n      templateInfo.nextSibling = templateInfo.previousSibling = null;\n      // Remove stamped nodes\n      let nodes = templateInfo.childNodes;\n      for (let i=0; i<nodes.length; i++) {\n        let node = nodes[i];\n        wrap(wrap(node).parentNode).removeChild(node);\n      }\n    }\n\n    /**\n     * Overrides default `TemplateStamp` implementation to add support for\n     * parsing bindings from `TextNode`'s' `textContent`.  A `bindings`\n     * array is added to `nodeInfo` and populated with binding metadata\n     * with information capturing the binding target, and a `parts` array\n     * with one or more metadata objects capturing the source(s) of the\n     * binding.\n     *\n     * @param {Node} node Node to parse\n     * @param {TemplateInfo} templateInfo Template metadata for current template\n     * @param {NodeInfo} nodeInfo Node metadata for current template node\n     * @return {boolean} `true` if the visited node added node-specific\n     *   metadata to `nodeInfo`\n     * @protected\n     * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do\n     * @nocollapse\n     */\n    static _parseTemplateNode(node, templateInfo, nodeInfo) {\n      // TODO(https://github.com/google/closure-compiler/issues/3240):\n      //     Change back to just super.methodCall()\n      let noted = propertyEffectsBase._parseTemplateNode.call(\n        this, node, templateInfo, nodeInfo);\n      if (node.nodeType === Node.TEXT_NODE) {\n        let parts = this._parseBindings(node.textContent, templateInfo);\n        if (parts) {\n          // Initialize the textContent with any literal parts\n          // NOTE: default to a space here so the textNode remains; some browsers\n          // (IE) omit an empty textNode following cloneNode/importNode.\n          node.textContent = literalFromParts(parts) || ' ';\n          addBinding(this, templateInfo, nodeInfo, 'text', 'textContent', parts);\n          noted = true;\n        }\n      }\n      return noted;\n    }\n\n    /**\n     * Overrides default `TemplateStamp` implementation to add support for\n     * parsing bindings from attributes.  A `bindings`\n     * array is added to `nodeInfo` and populated with binding metadata\n     * with information capturing the binding target, and a `parts` array\n     * with one or more metadata objects capturing the source(s) of the\n     * binding.\n     *\n     * @param {Element} node Node to parse\n     * @param {TemplateInfo} templateInfo Template metadata for current template\n     * @param {NodeInfo} nodeInfo Node metadata for current template node\n     * @param {string} name Attribute name\n     * @param {string} value Attribute value\n     * @return {boolean} `true` if the visited node added node-specific\n     *   metadata to `nodeInfo`\n     * @protected\n     * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do\n     * @nocollapse\n     */\n    static _parseTemplateNodeAttribute(node, templateInfo, nodeInfo, name, value) {\n      let parts = this._parseBindings(value, templateInfo);\n      if (parts) {\n        // Attribute or property\n        let origName = name;\n        let kind = 'property';\n        // The only way we see a capital letter here is if the attr has\n        // a capital letter in it per spec. In this case, to make sure\n        // this binding works, we go ahead and make the binding to the attribute.\n        if (capitalAttributeRegex.test(name)) {\n          kind = 'attribute';\n        } else if (name[name.length-1] == '$') {\n          name = name.slice(0, -1);\n          kind = 'attribute';\n        }\n        // Initialize attribute bindings with any literal parts\n        let literal = literalFromParts(parts);\n        if (literal && kind == 'attribute') {\n          // Ensure a ShadyCSS template scoped style is not removed\n          // when a class$ binding's initial literal value is set.\n          if (name == 'class' && node.hasAttribute('class')) {\n            literal += ' ' + node.getAttribute(name);\n          }\n          node.setAttribute(name, literal);\n        }\n        // support disable-upgrade\n        if (kind == 'attribute' && origName == 'disable-upgrade$') {\n          node.setAttribute(name, '');\n        }\n        // Clear attribute before removing, since IE won't allow removing\n        // `value` attribute if it previously had a value (can't\n        // unconditionally set '' before removing since attributes with `$`\n        // can't be set using setAttribute)\n        if (node.localName === 'input' && origName === 'value') {\n          node.setAttribute(origName, '');\n        }\n        // Remove annotation\n        node.removeAttribute(origName);\n        // Case hackery: attributes are lower-case, but bind targets\n        // (properties) are case sensitive. Gambit is to map dash-case to\n        // camel-case: `foo-bar` becomes `fooBar`.\n        // Attribute bindings are excepted.\n        if (kind === 'property') {\n          name = dashToCamelCase(name);\n        }\n        addBinding(this, templateInfo, nodeInfo, kind, name, parts, literal);\n        return true;\n      } else {\n        // TODO(https://github.com/google/closure-compiler/issues/3240):\n        //     Change back to just super.methodCall()\n        return propertyEffectsBase._parseTemplateNodeAttribute.call(\n          this, node, templateInfo, nodeInfo, name, value);\n      }\n    }\n\n    /**\n     * Overrides default `TemplateStamp` implementation to add support for\n     * binding the properties that a nested template depends on to the template\n     * as `_host_<property>`.\n     *\n     * @param {Node} node Node to parse\n     * @param {TemplateInfo} templateInfo Template metadata for current template\n     * @param {NodeInfo} nodeInfo Node metadata for current template node\n     * @return {boolean} `true` if the visited node added node-specific\n     *   metadata to `nodeInfo`\n     * @protected\n     * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do\n     * @nocollapse\n     */\n    static _parseTemplateNestedTemplate(node, templateInfo, nodeInfo) {\n      // TODO(https://github.com/google/closure-compiler/issues/3240):\n      //     Change back to just super.methodCall()\n      let noted = propertyEffectsBase._parseTemplateNestedTemplate.call(\n        this, node, templateInfo, nodeInfo);\n      const parent = node.parentNode;\n      const nestedTemplateInfo = nodeInfo.templateInfo;\n      const isDomIf = parent.localName === 'dom-if';\n      const isDomRepeat = parent.localName === 'dom-repeat';\n      // Remove nested template and redirect its host bindings & templateInfo\n      // onto the parent (dom-if/repeat element)'s nodeInfo\n      if (removeNestedTemplates && (isDomIf || isDomRepeat)) {\n        parent.removeChild(node);\n        // Use the parent's nodeInfo (for the dom-if/repeat) to record the\n        // templateInfo, and use that for any host property bindings below\n        nodeInfo = nodeInfo.parentInfo;\n        nodeInfo.templateInfo = nestedTemplateInfo;\n        // Ensure the parent dom-if/repeat is noted since it now may have host\n        // bindings; it may not have been if it did not have its own bindings\n        nodeInfo.noted = true;\n        noted = false;\n      }\n      // Merge host props into outer template and add bindings\n      let hostProps = nestedTemplateInfo.hostProps;\n      if (fastDomIf && isDomIf) {\n        // `fastDomIf` mode uses runtime-template stamping to add accessors/\n        // effects to properties used in its template; as such we don't need to\n        // tax the host element with `_host_` bindings for the `dom-if`.\n        // However, in the event it is nested in a `dom-repeat`, it is still\n        // important that its host properties are added to the\n        // TemplateInstance's `hostProps` so that they are forwarded to the\n        // TemplateInstance.\n        if (hostProps) {\n          templateInfo.hostProps =\n            Object.assign(templateInfo.hostProps || {}, hostProps);\n          // Ensure the dom-if is noted so that it has a __dataHost, since\n          // `fastDomIf` uses the host for runtime template stamping; note this\n          // was already ensured above in the `removeNestedTemplates` case\n          if (!removeNestedTemplates) {\n            nodeInfo.parentInfo.noted = true;\n          }\n        }\n      } else {\n        let mode = '{';\n        for (let source in hostProps) {\n          let parts = [{ mode, source, dependencies: [source], hostProp: true }];\n          addBinding(this, templateInfo, nodeInfo, 'property', '_host_' + source, parts);\n        }\n      }\n      return noted;\n    }\n\n    /**\n     * Called to parse text in a template (either attribute values or\n     * textContent) into binding metadata.\n     *\n     * Any overrides of this method should return an array of binding part\n     * metadata  representing one or more bindings found in the provided text\n     * and any \"literal\" text in between.  Any non-literal parts will be passed\n     * to `_evaluateBinding` when any dependencies change.  The only required\n     * fields of each \"part\" in the returned array are as follows:\n     *\n     * - `dependencies` - Array containing trigger metadata for each property\n     *   that should trigger the binding to update\n     * - `literal` - String containing text if the part represents a literal;\n     *   in this case no `dependencies` are needed\n     *\n     * Additional metadata for use by `_evaluateBinding` may be provided in\n     * each part object as needed.\n     *\n     * The default implementation handles the following types of bindings\n     * (one or more may be intermixed with literal strings):\n     * - Property binding: `[[prop]]`\n     * - Path binding: `[[object.prop]]`\n     * - Negated property or path bindings: `[[!prop]]` or `[[!object.prop]]`\n     * - Two-way property or path bindings (supports negation):\n     *   `{{prop}}`, `{{object.prop}}`, `{{!prop}}` or `{{!object.prop}}`\n     * - Inline computed method (supports negation):\n     *   `[[compute(a, 'literal', b)]]`, `[[!compute(a, 'literal', b)]]`\n     *\n     * The default implementation uses a regular expression for best\n     * performance. However, the regular expression uses a white-list of\n     * allowed characters in a data-binding, which causes problems for\n     * data-bindings that do use characters not in this white-list.\n     *\n     * Instead of updating the white-list with all allowed characters,\n     * there is a StrictBindingParser (see lib/mixins/strict-binding-parser)\n     * that uses a state machine instead. This state machine is able to handle\n     * all characters. However, it is slightly less performant, therefore we\n     * extracted it into a separate optional mixin.\n     *\n     * @param {string} text Text to parse from attribute or textContent\n     * @param {Object} templateInfo Current template metadata\n     * @return {Array<!BindingPart>} Array of binding part metadata\n     * @protected\n     * @nocollapse\n     */\n    static _parseBindings(text, templateInfo) {\n      let parts = [];\n      let lastIndex = 0;\n      let m;\n      // Example: \"literal1{{prop}}literal2[[!compute(foo,bar)]]final\"\n      // Regex matches:\n      //        Iteration 1:  Iteration 2:\n      // m[1]: '{{'          '[['\n      // m[2]: ''            '!'\n      // m[3]: 'prop'        'compute(foo,bar)'\n      while ((m = bindingRegex.exec(text)) !== null) {\n        // Add literal part\n        if (m.index > lastIndex) {\n          parts.push({literal: text.slice(lastIndex, m.index)});\n        }\n        // Add binding part\n        let mode = m[1][0];\n        let negate = Boolean(m[2]);\n        let source = m[3].trim();\n        let customEvent = false, notifyEvent = '', colon = -1;\n        if (mode == '{' && (colon = source.indexOf('::')) > 0) {\n          notifyEvent = source.substring(colon + 2);\n          source = source.substring(0, colon);\n          customEvent = true;\n        }\n        let signature = parseMethod(source);\n        let dependencies = [];\n        if (signature) {\n          // Inline computed function\n          let {args, methodName} = signature;\n          for (let i=0; i<args.length; i++) {\n            let arg = args[i];\n            if (!arg.literal) {\n              dependencies.push(arg);\n            }\n          }\n          let dynamicFns = templateInfo.dynamicFns;\n          if (dynamicFns && dynamicFns[methodName] || signature.static) {\n            dependencies.push(methodName);\n            signature.dynamicFn = true;\n          }\n        } else {\n          // Property or path\n          dependencies.push(source);\n        }\n        parts.push({\n          source, mode, negate, customEvent, signature, dependencies,\n          event: notifyEvent\n        });\n        lastIndex = bindingRegex.lastIndex;\n      }\n      // Add a final literal part\n      if (lastIndex && lastIndex < text.length) {\n        let literal = text.substring(lastIndex);\n        if (literal) {\n          parts.push({\n            literal: literal\n          });\n        }\n      }\n      if (parts.length) {\n        return parts;\n      } else {\n        return null;\n      }\n    }\n\n    /**\n     * Called to evaluate a previously parsed binding part based on a set of\n     * one or more changed dependencies.\n     *\n     * @param {!Polymer_PropertyEffects} inst Element that should be used as\n     *     scope for binding dependencies\n     * @param {BindingPart} part Binding part metadata\n     * @param {string} path Property/path that triggered this effect\n     * @param {Object} props Bag of current property changes\n     * @param {Object} oldProps Bag of previous values for changed properties\n     * @param {boolean} hasPaths True with `props` contains one or more paths\n     * @return {*} Value the binding part evaluated to\n     * @protected\n     * @nocollapse\n     */\n    static _evaluateBinding(inst, part, path, props, oldProps, hasPaths) {\n      let value;\n      if (part.signature) {\n        value = runMethodEffect(inst, path, props, oldProps, part.signature);\n      } else if (path != part.source) {\n        value = get(inst, part.source);\n      } else {\n        if (hasPaths && isPath(path)) {\n          value = get(inst, path);\n        } else {\n          value = inst.__data[path];\n        }\n      }\n      if (part.negate) {\n        value = !value;\n      }\n      return value;\n    }\n\n  }\n\n  return PropertyEffects;\n});\n\n/**\n * Stack for enqueuing client dom created by a host element.\n *\n * By default elements are flushed via `_flushProperties` when\n * `connectedCallback` is called. Elements attach their client dom to\n * themselves at `ready` time which results from this first flush.\n * This provides an ordering guarantee that the client dom an element\n * creates is flushed before the element itself (i.e. client `ready`\n * fires before host `ready`).\n *\n * However, if `_flushProperties` is called *before* an element is connected,\n * as for example `Templatize` does, this ordering guarantee cannot be\n * satisfied because no elements are connected. (Note: Bound elements that\n * receive data do become enqueued clients and are properly ordered but\n * unbound elements are not.)\n *\n * To maintain the desired \"client before host\" ordering guarantee for this\n * case we rely on the \"host stack. Client nodes registers themselves with\n * the creating host element when created. This ensures that all client dom\n * is readied in the proper order, maintaining the desired guarantee.\n *\n * @private\n */\nconst hostStack = [];\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport '../utils/boot.js';\n\nimport { dedupingMixin } from '../utils/mixin.js';\nimport { register, incrementInstanceCount } from '../utils/telemetry.js';\nimport { PropertiesChanged } from './properties-changed.js';\n\n/**\n * Creates a copy of `props` with each property normalized such that\n * upgraded it is an object with at least a type property { type: Type}.\n *\n * @param {!Object} props Properties to normalize\n * @return {!Object} Copy of input `props` with normalized properties that\n * are in the form {type: Type}\n * @private\n */\nfunction normalizeProperties(props) {\n  const output = {};\n  for (let p in props) {\n    const o = props[p];\n    output[p] = (typeof o === 'function') ? {type: o} : o;\n  }\n  return output;\n}\n\n/**\n * Mixin that provides a minimal starting point to using the PropertiesChanged\n * mixin by providing a mechanism to declare properties in a static\n * getter (e.g. static get properties() { return { foo: String } }). Changes\n * are reported via the `_propertiesChanged` method.\n *\n * This mixin provides no specific support for rendering. Users are expected\n * to create a ShadowRoot and put content into it and update it in whatever\n * way makes sense. This can be done in reaction to properties changing by\n * implementing `_propertiesChanged`.\n *\n * @mixinFunction\n * @polymer\n * @appliesMixin PropertiesChanged\n * @summary Mixin that provides a minimal starting point for using\n * the PropertiesChanged mixin by providing a declarative `properties` object.\n * @template T\n * @param {function(new:T)} superClass Class to apply mixin to.\n * @return {function(new:T)} superClass with mixin applied.\n */\nexport const PropertiesMixin = dedupingMixin(superClass => {\n\n /**\n  * @constructor\n  * @implements {Polymer_PropertiesChanged}\n  * @private\n  */\n const base = PropertiesChanged(superClass);\n\n /**\n  * Returns the super class constructor for the given class, if it is an\n  * instance of the PropertiesMixin.\n  *\n  * @param {!PropertiesMixinConstructor} constructor PropertiesMixin constructor\n  * @return {?PropertiesMixinConstructor} Super class constructor\n  */\n function superPropertiesClass(constructor) {\n   const superCtor = Object.getPrototypeOf(constructor);\n\n   // Note, the `PropertiesMixin` class below only refers to the class\n   // generated by this call to the mixin; the instanceof test only works\n   // because the mixin is deduped and guaranteed only to apply once, hence\n   // all constructors in a proto chain will see the same `PropertiesMixin`\n   return (superCtor.prototype instanceof PropertiesMixin) ?\n     /** @type {!PropertiesMixinConstructor} */ (superCtor) : null;\n }\n\n /**\n  * Returns a memoized version of the `properties` object for the\n  * given class. Properties not in object format are converted to at\n  * least {type}.\n  *\n  * @param {PropertiesMixinConstructor} constructor PropertiesMixin constructor\n  * @return {Object} Memoized properties object\n  */\n function ownProperties(constructor) {\n   if (!constructor.hasOwnProperty(JSCompiler_renameProperty('__ownProperties', constructor))) {\n     let props = null;\n\n     if (constructor.hasOwnProperty(JSCompiler_renameProperty('properties', constructor))) {\n       const properties = constructor.properties;\n\n       if (properties) {\n        props = normalizeProperties(properties);\n       }\n     }\n\n     constructor.__ownProperties = props;\n   }\n   return constructor.__ownProperties;\n }\n\n /**\n  * @polymer\n  * @mixinClass\n  * @extends {base}\n  * @implements {Polymer_PropertiesMixin}\n  * @unrestricted\n  */\n class PropertiesMixin extends base {\n\n   /**\n    * Implements standard custom elements getter to observes the attributes\n    * listed in `properties`.\n    * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do\n    * @nocollapse\n    */\n   static get observedAttributes() {\n     if (!this.hasOwnProperty(JSCompiler_renameProperty('__observedAttributes', this))) {\n       register(this.prototype);\n       const props = this._properties;\n       this.__observedAttributes = props ? Object.keys(props).map(p => this.prototype._addPropertyToAttributeMap(p)) : [];\n     }\n     return this.__observedAttributes;\n   }\n\n   /**\n    * Finalizes an element definition, including ensuring any super classes\n    * are also finalized. This includes ensuring property\n    * accessors exist on the element prototype. This method calls\n    * `_finalizeClass` to finalize each constructor in the prototype chain.\n    * @return {void}\n    * @nocollapse\n    */\n   static finalize() {\n     if (!this.hasOwnProperty(JSCompiler_renameProperty('__finalized', this))) {\n       const superCtor = superPropertiesClass(/** @type {!PropertiesMixinConstructor} */(this));\n       if (superCtor) {\n         superCtor.finalize();\n       }\n       this.__finalized = true;\n       this._finalizeClass();\n     }\n   }\n\n   /**\n    * Finalize an element class. This includes ensuring property\n    * accessors exist on the element prototype. This method is called by\n    * `finalize` and finalizes the class constructor.\n    *\n    * @protected\n    * @nocollapse\n    */\n   static _finalizeClass() {\n     const props = ownProperties(/** @type {!PropertiesMixinConstructor} */(this));\n     if (props) {\n       /** @type {?} */ (this).createProperties(props);\n     }\n   }\n\n   /**\n    * Returns a memoized version of all properties, including those inherited\n    * from super classes. Properties not in object format are converted to\n    * at least {type}.\n    *\n    * @return {Object} Object containing properties for this class\n    * @protected\n    * @nocollapse\n    */\n   static get _properties() {\n     if (!this.hasOwnProperty(\n       JSCompiler_renameProperty('__properties', this))) {\n       const superCtor = superPropertiesClass(/** @type {!PropertiesMixinConstructor} */(this));\n       this.__properties = Object.assign({},\n         superCtor && superCtor._properties,\n         ownProperties(/** @type {PropertiesMixinConstructor} */(this)));\n     }\n     return this.__properties;\n   }\n\n   /**\n    * Overrides `PropertiesChanged` method to return type specified in the\n    * static `properties` object for the given property.\n    * @param {string} name Name of property\n    * @return {*} Type to which to deserialize attribute\n    *\n    * @protected\n    * @nocollapse\n    */\n   static typeForProperty(name) {\n     const info = this._properties[name];\n     return info && info.type;\n   }\n\n   /**\n    * Overrides `PropertiesChanged` method and adds a call to\n    * `finalize` which lazily configures the element's property accessors.\n    * @override\n    * @return {void}\n    */\n   _initializeProperties() {\n     incrementInstanceCount();\n     this.constructor.finalize();\n     super._initializeProperties();\n   }\n\n   /**\n    * Called when the element is added to a document.\n    * Calls `_enableProperties` to turn on property system from\n    * `PropertiesChanged`.\n    * @suppress {missingProperties} Super may or may not implement the callback\n    * @return {void}\n    * @override\n    */\n   connectedCallback() {\n     if (super.connectedCallback) {\n       super.connectedCallback();\n     }\n     this._enableProperties();\n   }\n\n   /**\n    * Called when the element is removed from a document\n    * @suppress {missingProperties} Super may or may not implement the callback\n    * @return {void}\n    * @override\n    */\n   disconnectedCallback() {\n     if (super.disconnectedCallback) {\n       super.disconnectedCallback();\n     }\n   }\n\n }\n\n return PropertiesMixin;\n\n});\n","/**\n * @fileoverview\n * @suppress {checkPrototypalTypes}\n * @license Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt The complete set of authors may be found\n * at http://polymer.github.io/AUTHORS.txt The complete set of contributors may\n * be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by\n * Google as part of the polymer project is also subject to an additional IP\n * rights grant found at http://polymer.github.io/PATENTS.txt\n */\nimport '../utils/boot.js';\n\nimport { rootPath, strictTemplatePolicy, allowTemplateFromDomModule, legacyOptimizations, legacyWarnings, syncInitialRender, supportsAdoptingStyleSheets, useAdoptedStyleSheetsWithBuiltCSS } from '../utils/settings.js';\nimport { dedupingMixin } from '../utils/mixin.js';\nimport { stylesFromTemplate, stylesFromModuleImports } from '../utils/style-gather.js';\nimport { pathFromUrl, resolveCss, resolveUrl } from '../utils/resolve-url.js';\nimport { DomModule } from '../elements/dom-module.js';\nimport { PropertyEffects } from './property-effects.js';\nimport { PropertiesMixin } from './properties-mixin.js';\nimport { wrap } from '../utils/wrap.js';\n\n/**\n * Current Polymer version in Semver notation.\n * @type {string} Semver notation of the current version of Polymer.\n */\nexport const version = '3.5.1';\n\nexport const builtCSS = window.ShadyCSS && window.ShadyCSS['cssBuild'];\n\n/**\n * Element class mixin that provides the core API for Polymer's meta-programming\n * features including template stamping, data-binding, attribute deserialization,\n * and property change observation.\n *\n * Subclassers may provide the following static getters to return metadata\n * used to configure Polymer's features for the class:\n *\n * - `static get is()`: When the template is provided via a `dom-module`,\n *   users should return the `dom-module` id from a static `is` getter.  If\n *   no template is needed or the template is provided directly via the\n *   `template` getter, there is no need to define `is` for the element.\n *\n * - `static get template()`: Users may provide the template directly (as\n *   opposed to via `dom-module`) by implementing a static `template` getter.\n *   The getter must return an `HTMLTemplateElement`.\n *\n * - `static get properties()`: Should return an object describing\n *   property-related metadata used by Polymer features (key: property name\n *   value: object containing property metadata). Valid keys in per-property\n *   metadata include:\n *   - `type` (String|Number|Object|Array|...): Used by\n *     `attributeChangedCallback` to determine how string-based attributes\n *     are deserialized to JavaScript property values.\n *   - `notify` (boolean): Causes a change in the property to fire a\n *     non-bubbling event called `<property>-changed`. Elements that have\n *     enabled two-way binding to the property use this event to observe changes.\n *   - `readOnly` (boolean): Creates a getter for the property, but no setter.\n *     To set a read-only property, use the private setter method\n *     `_setProperty(property, value)`.\n *   - `observer` (string): Observer method name that will be called when\n *     the property changes. The arguments of the method are\n *     `(value, previousValue)`.\n *   - `computed` (string): String describing method and dependent properties\n *     for computing the value of this property (e.g. `'computeFoo(bar, zot)'`).\n *     Computed properties are read-only by default and can only be changed\n *     via the return value of the computing method.\n *\n * - `static get observers()`: Array of strings describing multi-property\n *   observer methods and their dependent properties (e.g.\n *   `'observeABC(a, b, c)'`).\n *\n * The base class provides default implementations for the following standard\n * custom element lifecycle callbacks; users may override these, but should\n * call the super method to ensure\n * - `constructor`: Run when the element is created or upgraded\n * - `connectedCallback`: Run each time the element is connected to the\n *   document\n * - `disconnectedCallback`: Run each time the element is disconnected from\n *   the document\n * - `attributeChangedCallback`: Run each time an attribute in\n *   `observedAttributes` is set or removed (note: this element's default\n *   `observedAttributes` implementation will automatically return an array\n *   of dash-cased attributes based on `properties`)\n *\n * @mixinFunction\n * @polymer\n * @appliesMixin PropertyEffects\n * @appliesMixin PropertiesMixin\n * @property rootPath {string} Set to the value of `rootPath`,\n *   which defaults to the main document path\n * @property importPath {string} Set to the value of the class's static\n *   `importPath` property, which defaults to the path of this element's\n *   `dom-module` (when `is` is used), but can be overridden for other\n *   import strategies.\n * @summary Element class mixin that provides the core API for Polymer's\n * meta-programming features.\n * @template T\n * @param {function(new:T)} superClass Class to apply mixin to.\n * @return {function(new:T)} superClass with mixin applied.\n */\nexport const ElementMixin = dedupingMixin(base => {\n  /**\n   * @constructor\n   * @implements {Polymer_PropertyEffects}\n   * @implements {Polymer_PropertiesMixin}\n   * @extends {HTMLElement}\n   * @private\n   */\n  const polymerElementBase = PropertiesMixin(PropertyEffects(base));\n\n  /**\n   * Returns a list of properties with default values.\n   * This list is created as an optimization since it is a subset of\n   * the list returned from `_properties`.\n   * This list is used in `_initializeProperties` to set property defaults.\n   *\n   * @param {PolymerElementConstructor} constructor Element class\n   * @return {PolymerElementProperties} Flattened properties for this class\n   *   that have default values\n   * @private\n   */\n  function propertyDefaults(constructor) {\n    if (!constructor.hasOwnProperty(\n      JSCompiler_renameProperty('__propertyDefaults', constructor))) {\n      constructor.__propertyDefaults = null;\n      let props = constructor._properties;\n      for (let p in props) {\n        let info = props[p];\n        if ('value' in info) {\n          constructor.__propertyDefaults = constructor.__propertyDefaults || {};\n          constructor.__propertyDefaults[p] = info;\n        }\n      }\n    }\n    return constructor.__propertyDefaults;\n  }\n\n  /**\n   * Returns a memoized version of the `observers` array.\n   * @param {PolymerElementConstructor} constructor Element class\n   * @return {Array} Array containing own observers for the given class\n   * @protected\n   */\n  function ownObservers(constructor) {\n    if (!constructor.hasOwnProperty(\n      JSCompiler_renameProperty('__ownObservers', constructor))) {\n      constructor.__ownObservers =\n          constructor.hasOwnProperty(\n              JSCompiler_renameProperty('observers', constructor)) ?\n          /** @type {PolymerElementConstructor} */ (constructor).observers :\n          null;\n    }\n    return constructor.__ownObservers;\n  }\n\n  /**\n   * Creates effects for a property.\n   *\n   * Note, once a property has been set to\n   * `readOnly`, `computed`, `reflectToAttribute`, or `notify`\n   * these values may not be changed. For example, a subclass cannot\n   * alter these settings. However, additional `observers` may be added\n   * by subclasses.\n   *\n   * The info object should contain property metadata as follows:\n   *\n   * * `type`: {function} type to which an attribute matching the property\n   * is deserialized. Note the property is camel-cased from a dash-cased\n   * attribute. For example, 'foo-bar' attribute is deserialized to a\n   * property named 'fooBar'.\n   *\n   * * `readOnly`: {boolean} creates a readOnly property and\n   * makes a private setter for the private of the form '_setFoo' for a\n   * property 'foo',\n   *\n   * * `computed`: {string} creates a computed property. A computed property\n   * is also automatically set to `readOnly: true`. The value is calculated\n   * by running a method and arguments parsed from the given string. For\n   * example 'compute(foo)' will compute a given property when the\n   * 'foo' property changes by executing the 'compute' method. This method\n   * must return the computed value.\n   *\n   * * `reflectToAttribute`: {boolean} If true, the property value is reflected\n   * to an attribute of the same name. Note, the attribute is dash-cased\n   * so a property named 'fooBar' is reflected as 'foo-bar'.\n   *\n   * * `notify`: {boolean} sends a non-bubbling notification event when\n   * the property changes. For example, a property named 'foo' sends an\n   * event named 'foo-changed' with `event.detail` set to the value of\n   * the property.\n   *\n   * * observer: {string} name of a method that runs when the property\n   * changes. The arguments of the method are (value, previousValue).\n   *\n   * Note: Users may want control over modifying property\n   * effects via subclassing. For example, a user might want to make a\n   * reflectToAttribute property not do so in a subclass. We've chosen to\n   * disable this because it leads to additional complication.\n   * For example, a readOnly effect generates a special setter. If a subclass\n   * disables the effect, the setter would fail unexpectedly.\n   * Based on feedback, we may want to try to make effects more malleable\n   * and/or provide an advanced api for manipulating them.\n   *\n   * @param {!PolymerElement} proto Element class prototype to add accessors\n   *   and effects to\n   * @param {string} name Name of the property.\n   * @param {Object} info Info object from which to create property effects.\n   * Supported keys:\n   * @param {Object} allProps Flattened map of all properties defined in this\n   *   element (including inherited properties)\n   * @return {void}\n   * @private\n   */\n  function createPropertyFromConfig(proto, name, info, allProps) {\n    // computed forces readOnly...\n    if (info.computed) {\n      info.readOnly = true;\n    }\n    // Note, since all computed properties are readOnly, this prevents\n    // adding additional computed property effects (which leads to a confusing\n    // setup where multiple triggers for setting a property)\n    // While we do have `hasComputedEffect` this is set on the property's\n    // dependencies rather than itself.\n    if (info.computed) {\n      if (proto._hasReadOnlyEffect(name)) {\n        console.warn(`Cannot redefine computed property '${name}'.`);\n      } else {\n        proto._createComputedProperty(name, info.computed, allProps);\n      }\n    }\n    if (info.readOnly && !proto._hasReadOnlyEffect(name)) {\n      proto._createReadOnlyProperty(name, !info.computed);\n    } else if (info.readOnly === false && proto._hasReadOnlyEffect(name)) {\n      console.warn(`Cannot make readOnly property '${name}' non-readOnly.`);\n    }\n    if (info.reflectToAttribute && !proto._hasReflectEffect(name)) {\n      proto._createReflectedProperty(name);\n    } else if (info.reflectToAttribute === false && proto._hasReflectEffect(name)) {\n      console.warn(`Cannot make reflected property '${name}' non-reflected.`);\n    }\n    if (info.notify && !proto._hasNotifyEffect(name)) {\n      proto._createNotifyingProperty(name);\n    } else if (info.notify === false && proto._hasNotifyEffect(name)) {\n      console.warn(`Cannot make notify property '${name}' non-notify.`);\n    }\n    // always add observer\n    if (info.observer) {\n      proto._createPropertyObserver(name, info.observer, allProps[info.observer]);\n    }\n    // always create the mapping from attribute back to property for deserialization.\n    proto._addPropertyToAttributeMap(name);\n  }\n\n  /**\n   * Process all style elements in the element template. Styles with the\n   * `include` attribute are processed such that any styles in\n   * the associated \"style modules\" are included in the element template.\n   * @param {PolymerElementConstructor} klass Element class\n   * @param {!HTMLTemplateElement} template Template to process\n   * @param {string} is Name of element\n   * @param {string} baseURI Base URI for element\n   * @private\n   */\n  function processElementStyles(klass, template, is, baseURI) {\n    if (!builtCSS) {\n      const templateStyles = template.content.querySelectorAll('style');\n      const stylesWithImports = stylesFromTemplate(template);\n      // insert styles from <link rel=\"import\" type=\"css\"> at the top of the template\n      const linkedStyles = stylesFromModuleImports(is);\n      const firstTemplateChild = template.content.firstElementChild;\n      for (let idx = 0; idx < linkedStyles.length; idx++) {\n        let s = linkedStyles[idx];\n        s.textContent = klass._processStyleText(s.textContent, baseURI);\n        template.content.insertBefore(s, firstTemplateChild);\n      }\n      // keep track of the last \"concrete\" style in the template we have encountered\n      let templateStyleIndex = 0;\n      // ensure all gathered styles are actually in this template.\n      for (let i = 0; i < stylesWithImports.length; i++) {\n        let s = stylesWithImports[i];\n        let templateStyle = templateStyles[templateStyleIndex];\n        // if the style is not in this template, it's been \"included\" and\n        // we put a clone of it in the template before the style that included it\n        if (templateStyle !== s) {\n          s = s.cloneNode(true);\n          templateStyle.parentNode.insertBefore(s, templateStyle);\n        } else {\n          templateStyleIndex++;\n        }\n        s.textContent = klass._processStyleText(s.textContent, baseURI);\n      }\n    }\n    if (window.ShadyCSS) {\n      window.ShadyCSS.prepareTemplate(template, is);\n    }\n    // Support for `adoptedStylesheets` relies on using native Shadow DOM\n    // and built CSS. Built CSS is required because runtime transformation of\n    // `@apply` is not supported. This is because ShadyCSS relies on being able\n    // to update a `style` element in the element template and this is\n    // removed when using `adoptedStyleSheets`.\n    // Note, it would be more efficient to allow style includes to become\n    // separate stylesheets; however, because of `@apply` these are\n    // potentially not shareable and sharing the ones that could be shared\n    // would require some coordination. To keep it simple, all the includes\n    // and styles are collapsed into a single shareable stylesheet.\n    if (useAdoptedStyleSheetsWithBuiltCSS && builtCSS &&\n        supportsAdoptingStyleSheets) {\n      // Remove styles in template and make a shareable stylesheet\n      const styles = template.content.querySelectorAll('style');\n      if (styles) {\n        let css = '';\n        Array.from(styles).forEach(s => {\n          css += s.textContent;\n          s.parentNode.removeChild(s);\n        });\n        klass._styleSheet = new CSSStyleSheet();\n        klass._styleSheet.replaceSync(css);\n      }\n    }\n  }\n\n  /**\n   * Look up template from dom-module for element\n   *\n   * @param {string} is Element name to look up\n   * @return {?HTMLTemplateElement|undefined} Template found in dom module, or\n   *   undefined if not found\n   * @protected\n   */\n  function getTemplateFromDomModule(is) {\n    let template = null;\n    // Under strictTemplatePolicy in 3.x+, dom-module lookup is only allowed\n    // when opted-in via allowTemplateFromDomModule\n    if (is && (!strictTemplatePolicy || allowTemplateFromDomModule)) {\n      template = /** @type {?HTMLTemplateElement} */ (\n          DomModule.import(is, 'template'));\n      // Under strictTemplatePolicy, require any element with an `is`\n      // specified to have a dom-module\n      if (strictTemplatePolicy && !template) {\n        throw new Error(`strictTemplatePolicy: expecting dom-module or null template for ${is}`);\n      }\n    }\n    return template;\n  }\n\n  /**\n   * @polymer\n   * @mixinClass\n   * @unrestricted\n   * @implements {Polymer_ElementMixin}\n   * @extends {polymerElementBase}\n   */\n  class PolymerElement extends polymerElementBase {\n\n    /**\n     * Current Polymer version in Semver notation.\n     * @type {string} Semver notation of the current version of Polymer.\n     * @nocollapse\n     */\n    static get polymerElementVersion() {\n      return version;\n    }\n\n    /**\n     * Override of PropertiesMixin _finalizeClass to create observers and\n     * find the template.\n     * @return {void}\n     * @protected\n     * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do\n     * @nocollapse\n     */\n    static _finalizeClass() {\n      // TODO(https://github.com/google/closure-compiler/issues/3240):\n      //     Change back to just super.methodCall()\n      polymerElementBase._finalizeClass.call(this);\n      const observers = ownObservers(this);\n      if (observers) {\n        this.createObservers(observers, this._properties);\n      }\n      this._prepareTemplate();\n    }\n\n    /** @nocollapse */\n    static _prepareTemplate() {\n      // note: create \"working\" template that is finalized at instance time\n      let template = /** @type {PolymerElementConstructor} */ (this).template;\n      if (template) {\n        if (typeof template === 'string') {\n          console.error('template getter must return HTMLTemplateElement');\n          template = null;\n        } else if (!legacyOptimizations) {\n          template = template.cloneNode(true);\n        }\n      }\n\n      /** @override */\n      this.prototype._template = template;\n    }\n\n    /**\n     * Override of PropertiesChanged createProperties to create accessors\n     * and property effects for all of the properties.\n     * @param {!Object} props .\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static createProperties(props) {\n      for (let p in props) {\n        createPropertyFromConfig(\n            /** @type {?} */ (this.prototype), p, props[p], props);\n      }\n    }\n\n    /**\n     * Creates observers for the given `observers` array.\n     * Leverages `PropertyEffects` to create observers.\n     * @param {Object} observers Array of observer descriptors for\n     *   this class\n     * @param {Object} dynamicFns Object containing keys for any properties\n     *   that are functions and should trigger the effect when the function\n     *   reference is changed\n     * @return {void}\n     * @protected\n     * @nocollapse\n     */\n    static createObservers(observers, dynamicFns) {\n      const proto = this.prototype;\n      for (let i=0; i < observers.length; i++) {\n        proto._createMethodObserver(observers[i], dynamicFns);\n      }\n    }\n\n    /**\n     * Returns the template that will be stamped into this element's shadow root.\n     *\n     * If a `static get is()` getter is defined, the default implementation will\n     * return the first `<template>` in a `dom-module` whose `id` matches this\n     * element's `is` (note that a `_template` property on the class prototype\n     * takes precedence over the `dom-module` template, to maintain legacy\n     * element semantics; a subclass will subsequently fall back to its super\n     * class template if neither a `prototype._template` or a `dom-module` for\n     * the class's `is` was found).\n     *\n     * Users may override this getter to return an arbitrary template\n     * (in which case the `is` getter is unnecessary). The template returned\n     * must be an `HTMLTemplateElement`.\n     *\n     * Note that when subclassing, if the super class overrode the default\n     * implementation and the subclass would like to provide an alternate\n     * template via a `dom-module`, it should override this getter and\n     * return `DomModule.import(this.is, 'template')`.\n     *\n     * If a subclass would like to modify the super class template, it should\n     * clone it rather than modify it in place.  If the getter does expensive\n     * work such as cloning/modifying a template, it should memoize the\n     * template for maximum performance:\n     *\n     *   let memoizedTemplate;\n     *   class MySubClass extends MySuperClass {\n     *     static get template() {\n     *       if (!memoizedTemplate) {\n     *         memoizedTemplate = super.template.cloneNode(true);\n     *         let subContent = document.createElement('div');\n     *         subContent.textContent = 'This came from MySubClass';\n     *         memoizedTemplate.content.appendChild(subContent);\n     *       }\n     *       return memoizedTemplate;\n     *     }\n     *   }\n     *\n     * @return {!HTMLTemplateElement|string} Template to be stamped\n     * @nocollapse\n     */\n    static get template() {\n      // Explanation of template-related properties:\n      // - constructor.template (this getter): the template for the class.\n      //     This can come from the prototype (for legacy elements), from a\n      //     dom-module, or from the super class's template (or can be overridden\n      //     altogether by the user)\n      // - constructor._template: memoized version of constructor.template\n      // - prototype._template: working template for the element, which will be\n      //     parsed and modified in place. It is a cloned version of\n      //     constructor.template, saved in _finalizeClass(). Note that before\n      //     this getter is called, for legacy elements this could be from a\n      //     _template field on the info object passed to Polymer(), a behavior,\n      //     or set in registered(); once the static getter runs, a clone of it\n      //     will overwrite it on the prototype as the working template.\n      if (!this.hasOwnProperty(JSCompiler_renameProperty('_template', this))) {\n        let protoTemplate = this.prototype.hasOwnProperty(\n          JSCompiler_renameProperty('_template', this.prototype)) ?\n          this.prototype._template : undefined;\n        // Accept a function for the legacy Polymer({_template:...}) field for\n        // lazy parsing\n        if (typeof protoTemplate === 'function') {\n          protoTemplate = protoTemplate();\n        }\n        this._template =\n          // If user has put template on prototype (e.g. in legacy via registered\n          // callback or info object), prefer that first. Note that `null` is\n          // used as a sentinel to indicate \"no template\" and can be used to\n          // override a super template, whereas `undefined` is used as a\n          // sentinel to mean \"fall-back to default template lookup\" via\n          // dom-module and/or super.template.\n          protoTemplate !== undefined ? protoTemplate :\n          // Look in dom-module associated with this element's is\n          ((this.hasOwnProperty(JSCompiler_renameProperty('is', this)) &&\n          (getTemplateFromDomModule(/** @type {PolymerElementConstructor}*/ (this).is))) ||\n          // Next look for superclass template (call the super impl this\n          // way so that `this` points to the superclass)\n          Object.getPrototypeOf(/** @type {PolymerElementConstructor}*/ (this).prototype).constructor.template);\n      }\n      return this._template;\n    }\n\n    /**\n     * Set the template.\n     *\n     * @param {!HTMLTemplateElement|string} value Template to set.\n     * @nocollapse\n     */\n    static set template(value) {\n      this._template = value;\n    }\n\n    /**\n     * Path matching the url from which the element was imported.\n     *\n     * This path is used to resolve url's in template style cssText.\n     * The `importPath` property is also set on element instances and can be\n     * used to create bindings relative to the import path.\n     *\n     * For elements defined in ES modules, users should implement\n     * `static get importMeta() { return import.meta; }`, and the default\n     * implementation of `importPath` will  return `import.meta.url`'s path.\n     * For elements defined in HTML imports, this getter will return the path\n     * to the document containing a `dom-module` element matching this\n     * element's static `is` property.\n     *\n     * Note, this path should contain a trailing `/`.\n     *\n     * @return {string} The import path for this element class\n     * @suppress {missingProperties}\n     * @nocollapse\n     */\n    static get importPath() {\n      if (!this.hasOwnProperty(JSCompiler_renameProperty('_importPath', this))) {\n        const meta = this.importMeta;\n        if (meta) {\n          this._importPath = pathFromUrl(meta.url);\n        } else {\n          const module = DomModule.import(/** @type {PolymerElementConstructor} */ (this).is);\n          this._importPath = (module && module.assetpath) ||\n            Object.getPrototypeOf(/** @type {PolymerElementConstructor}*/ (this).prototype).constructor.importPath;\n        }\n      }\n      return this._importPath;\n    }\n\n    constructor() {\n      super();\n      /** @type {HTMLTemplateElement} */\n      this._template;\n      /** @type {string} */\n      this._importPath;\n      /** @type {string} */\n      this.rootPath;\n      /** @type {string} */\n      this.importPath;\n      /** @type {StampedTemplate | HTMLElement | ShadowRoot} */\n      this.root;\n      /** @type {!Object<string, !Element>} */\n      this.$;\n    }\n\n    /**\n     * Overrides the default `PropertyAccessors` to ensure class\n     * metaprogramming related to property accessors and effects has\n     * completed (calls `finalize`).\n     *\n     * It also initializes any property defaults provided via `value` in\n     * `properties` metadata.\n     *\n     * @return {void}\n     * @override\n     * @suppress {invalidCasts,missingProperties} go/missingfnprops\n     */\n    _initializeProperties() {\n      this.constructor.finalize();\n      // note: finalize template when we have access to `localName` to\n      // avoid dependence on `is` for polyfilling styling.\n      this.constructor._finalizeTemplate(/** @type {!HTMLElement} */(this).localName);\n      super._initializeProperties();\n      // set path defaults\n      this.rootPath = rootPath;\n      this.importPath = this.constructor.importPath;\n      // apply property defaults...\n      let p$ = propertyDefaults(this.constructor);\n      if (!p$) {\n        return;\n      }\n      for (let p in p$) {\n        let info = p$[p];\n        if (this._canApplyPropertyDefault(p)) {\n          let value = typeof info.value == 'function' ?\n            info.value.call(this) :\n            info.value;\n          // Set via `_setProperty` if there is an accessor, to enable\n          // initializing readOnly property defaults\n          if (this._hasAccessor(p)) {\n            this._setPendingProperty(p, value, true);\n          } else {\n            this[p] = value;\n          }\n        }\n      }\n    }\n\n    /**\n     * Determines if a property dfeault can be applied. For example, this\n     * prevents a default from being applied when a property that has no\n     * accessor is overridden by its host before upgrade (e.g. via a binding).\n     * @override\n     * @param {string} property Name of the property\n     * @return {boolean} Returns true if the property default can be applied.\n     */\n    _canApplyPropertyDefault(property) {\n      return !this.hasOwnProperty(property);\n    }\n\n    /**\n     * Gather style text for a style element in the template.\n     *\n     * @param {string} cssText Text containing styling to process\n     * @param {string} baseURI Base URI to rebase CSS paths against\n     * @return {string} The processed CSS text\n     * @protected\n     * @nocollapse\n     */\n    static _processStyleText(cssText, baseURI) {\n      return resolveCss(cssText, baseURI);\n    }\n\n    /**\n    * Configures an element `proto` to function with a given `template`.\n    * The element name `is` and extends `ext` must be specified for ShadyCSS\n    * style scoping.\n    *\n    * @param {string} is Tag name (or type extension name) for this element\n    * @return {void}\n    * @protected\n    * @nocollapse\n    */\n    static _finalizeTemplate(is) {\n      /** @const {HTMLTemplateElement} */\n      const template = this.prototype._template;\n      if (template && !template.__polymerFinalized) {\n        template.__polymerFinalized = true;\n        const importPath = this.importPath;\n        const baseURI = importPath ? resolveUrl(importPath) : '';\n        // e.g. support `include=\"module-name\"`, and ShadyCSS\n        processElementStyles(this, template, is, baseURI);\n        this.prototype._bindTemplate(template);\n      }\n    }\n\n    /**\n     * Provides a default implementation of the standard Custom Elements\n     * `connectedCallback`.\n     *\n     * The default implementation enables the property effects system and\n     * flushes any pending properties, and updates shimmed CSS properties\n     * when using the ShadyCSS scoping/custom properties polyfill.\n     *\n     * @override\n     * @suppress {missingProperties, invalidCasts} Super may or may not\n     *     implement the callback\n     * @return {void}\n     */\n    connectedCallback() {\n      if (window.ShadyCSS && this._template) {\n        window.ShadyCSS.styleElement(/** @type {!HTMLElement} */(this));\n      }\n      super.connectedCallback();\n    }\n\n    /**\n     * Stamps the element template.\n     *\n     * @return {void}\n     * @override\n     */\n    ready() {\n      if (this._template) {\n        this.root = this._stampTemplate(this._template);\n        this.$ = this.root.$;\n      }\n      super.ready();\n    }\n\n    /**\n     * Implements `PropertyEffects`'s `_readyClients` call. Attaches\n     * element dom by calling `_attachDom` with the dom stamped from the\n     * element's template via `_stampTemplate`. Note that this allows\n     * client dom to be attached to the element prior to any observers\n     * running.\n     *\n     * @return {void}\n     * @override\n     */\n    _readyClients() {\n      if (this._template) {\n        this.root = this._attachDom(/** @type {StampedTemplate} */(this.root));\n      }\n      // The super._readyClients here sets the clients initialized flag.\n      // We must wait to do this until after client dom is created/attached\n      // so that this flag can be checked to prevent notifications fired\n      // during this process from being handled before clients are ready.\n      super._readyClients();\n    }\n\n\n    /**\n     * Attaches an element's stamped dom to itself. By default,\n     * this method creates a `shadowRoot` and adds the dom to it.\n     * However, this method may be overridden to allow an element\n     * to put its dom in another location.\n     *\n     * @override\n     * @throws {Error}\n     * @suppress {missingReturn}\n     * @param {StampedTemplate} dom to attach to the element.\n     * @return {ShadowRoot} node to which the dom has been attached.\n     */\n    _attachDom(dom) {\n      const n = wrap(this);\n      if (n.attachShadow) {\n        if (dom) {\n          if (!n.shadowRoot) {\n            n.attachShadow({mode: 'open', shadyUpgradeFragment: dom});\n            n.shadowRoot.appendChild(dom);\n            // When `adoptedStyleSheets` is supported a stylesheet is made\n            // available on the element constructor.\n            if (this.constructor._styleSheet) {\n              n.shadowRoot.adoptedStyleSheets = [this.constructor._styleSheet];\n            }\n          }\n          if (syncInitialRender && window.ShadyDOM) {\n            window.ShadyDOM.flushInitial(n.shadowRoot);\n          }\n          return n.shadowRoot;\n        }\n        return null;\n      } else {\n        throw new Error('ShadowDOM not available. ' +\n          // TODO(sorvell): move to compile-time conditional when supported\n        'PolymerElement can create dom as children instead of in ' +\n        'ShadowDOM by setting `this.root = this;\\` before \\`ready\\`.');\n      }\n    }\n\n    /**\n     * When using the ShadyCSS scoping and custom property shim, causes all\n     * shimmed styles in this element (and its subtree) to be updated\n     * based on current custom property values.\n     *\n     * The optional parameter overrides inline custom property styles with an\n     * object of properties where the keys are CSS properties, and the values\n     * are strings.\n     *\n     * Example: `this.updateStyles({'--color': 'blue'})`\n     *\n     * These properties are retained unless a value of `null` is set.\n     *\n     * Note: This function does not support updating CSS mixins.\n     * You can not dynamically change the value of an `@apply`.\n     *\n     * @override\n     * @param {Object=} properties Bag of custom property key/values to\n     *   apply to this element.\n     * @return {void}\n     * @suppress {invalidCasts}\n     */\n    updateStyles(properties) {\n      if (window.ShadyCSS) {\n        window.ShadyCSS.styleSubtree(/** @type {!HTMLElement} */(this), properties);\n      }\n    }\n\n    /**\n     * Rewrites a given URL relative to a base URL. The base URL defaults to\n     * the original location of the document containing the `dom-module` for\n     * this element. This method will return the same URL before and after\n     * bundling.\n     *\n     * Note that this function performs no resolution for URLs that start\n     * with `/` (absolute URLs) or `#` (hash identifiers).  For general purpose\n     * URL resolution, use `window.URL`.\n     *\n     * @override\n     * @param {string} url URL to resolve.\n     * @param {string=} base Optional base URL to resolve against, defaults\n     * to the element's `importPath`\n     * @return {string} Rewritten URL relative to base\n     */\n    resolveUrl(url, base) {\n      if (!base && this.importPath) {\n        base = resolveUrl(this.importPath);\n      }\n      return resolveUrl(url, base);\n    }\n\n    /**\n     * Overrides `PropertyEffects` to add map of dynamic functions on\n     * template info, for consumption by `PropertyEffects` template binding\n     * code. This map determines which method templates should have accessors\n     * created for them.\n     *\n     * @param {!HTMLTemplateElement} template Template\n     * @param {!TemplateInfo} templateInfo Template metadata for current template\n     * @param {!NodeInfo} nodeInfo Node metadata for current template.\n     * @return {boolean} .\n     * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do\n     * @nocollapse\n     */\n    static _parseTemplateContent(template, templateInfo, nodeInfo) {\n      templateInfo.dynamicFns = templateInfo.dynamicFns || this._properties;\n      // TODO(https://github.com/google/closure-compiler/issues/3240):\n      //     Change back to just super.methodCall()\n      return polymerElementBase._parseTemplateContent.call(\n        this, template, templateInfo, nodeInfo);\n    }\n\n    /**\n     * Overrides `PropertyEffects` to warn on use of undeclared properties in\n     * template.\n     *\n     * @param {Object} templateInfo Template metadata to add effect to\n     * @param {string} prop Property that should trigger the effect\n     * @param {Object=} effect Effect metadata object\n     * @return {void}\n     * @protected\n     * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do\n     * @nocollapse\n     */\n    static _addTemplatePropertyEffect(templateInfo, prop, effect) {\n      // Warn if properties are used in template without being declared.\n      // Properties must be listed in `properties` to be included in\n      // `observedAttributes` since CE V1 reads that at registration time, and\n      // since we want to keep template parsing lazy, we can't automatically\n      // add undeclared properties used in templates to `observedAttributes`.\n      // The warning is only enabled in `legacyOptimizations` mode, since\n      // we don't want to spam existing users who might have adopted the\n      // shorthand when attribute deserialization is not important.\n      if (legacyWarnings && !(prop in this._properties) &&\n          // Methods used in templates with no dependencies (or only literal\n          // dependencies) become accessors with template effects; ignore these\n          !(effect.info.part.signature && effect.info.part.signature.static) &&\n          // Warnings for bindings added to nested templates are handled by\n          // templatizer so ignore both the host-to-template bindings\n          // (`hostProp`) and TemplateInstance-to-child bindings\n          // (`nestedTemplate`)\n          !effect.info.part.hostProp && !templateInfo.nestedTemplate) {\n        console.warn(`Property '${prop}' used in template but not declared in 'properties'; ` +\n          `attribute will not be observed.`);\n      }\n      // TODO(https://github.com/google/closure-compiler/issues/3240):\n      //     Change back to just super.methodCall()\n      return polymerElementBase._addTemplatePropertyEffect.call(\n        this, templateInfo, prop, effect);\n    }\n\n  }\n\n  return PolymerElement;\n});\n\n/**\n * When using the ShadyCSS scoping and custom property shim, causes all\n * shimmed `styles` (via `custom-style`) in the document (and its subtree)\n * to be updated based on current custom property values.\n *\n * The optional parameter overrides inline custom property styles with an\n * object of properties where the keys are CSS properties, and the values\n * are strings.\n *\n * Example: `updateStyles({'--color': 'blue'})`\n *\n * These properties are retained unless a value of `null` is set.\n *\n * @param {Object=} props Bag of custom property key/values to\n *   apply to the document.\n * @return {void}\n */\nexport const updateStyles = function(props) {\n  if (window.ShadyCSS) {\n    window.ShadyCSS.styleDocument(props);\n  }\n};\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\n\n/**\n * Our TrustedTypePolicy for HTML which is declared using the Polymer html\n * template tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n *\n * @type {!TrustedTypePolicy|undefined}\n */\nconst policy = window.trustedTypes &&\n    trustedTypes.createPolicy('polymer-html-literal', {createHTML: (s) => s});\n\n/**\n * Class representing a static string value which can be used to filter\n * strings by asseting that they have been created via this class. The\n * `value` property returns the string passed to the constructor.\n */\nclass LiteralString {\n  /**\n   * @param {!ITemplateArray} strings Constant parts of tagged template literal\n   * @param {!Array<*>} values Variable parts of tagged template literal\n   */\n  constructor(strings, values) {\n    assertValidTemplateStringParameters(strings, values);\n    const string = values.reduce(\n        (acc, v, idx) => acc + literalValue(v) + strings[idx + 1], strings[0]);\n    /** @type {string} */\n    this.value = string.toString();\n  }\n  /**\n   * @return {string} LiteralString string value\n   * @override\n   */\n  toString() {\n    return this.value;\n  }\n}\n\n/**\n * @param {*} value Object to stringify into HTML\n * @return {string} HTML stringified form of `obj`\n */\nfunction literalValue(value) {\n  if (value instanceof LiteralString) {\n    return /** @type {!LiteralString} */(value).value;\n  } else {\n    throw new Error(\n        `non-literal value passed to Polymer's htmlLiteral function: ${value}`\n    );\n  }\n}\n\n/**\n * @param {*} value Object to stringify into HTML\n * @return {string} HTML stringified form of `obj`\n */\nfunction htmlValue(value) {\n  if (value instanceof HTMLTemplateElement) {\n    // This might be an mXSS risk – mainly in the case where this template\n    // contains untrusted content that was believed to be sanitized.\n    // However we can't just use the XMLSerializer here because it misencodes\n    // `>` characters inside style tags.\n    // For an example of an actual case that hit this encoding issue,\n    // see b/198592167\n    return /** @type {!HTMLTemplateElement } */(value).innerHTML;\n  } else if (value instanceof LiteralString) {\n    return literalValue(value);\n  } else {\n    throw new Error(\n        `non-template value passed to Polymer's html function: ${value}`);\n  }\n}\n\n/**\n * A template literal tag that creates an HTML <template> element from the\n * contents of the string.\n *\n * This allows you to write a Polymer Template in JavaScript.\n *\n * Templates can be composed by interpolating `HTMLTemplateElement`s in\n * expressions in the JavaScript template literal. The nested template's\n * `innerHTML` is included in the containing template.  The only other\n * values allowed in expressions are those returned from `htmlLiteral`\n * which ensures only literal values from JS source ever reach the HTML, to\n * guard against XSS risks.\n *\n * All other values are disallowed in expressions to help prevent XSS\n * attacks; however, `htmlLiteral` can be used to compose static\n * string values into templates. This is useful to compose strings into\n * places that do not accept html, like the css text of a `style`\n * element.\n *\n * Example:\n *\n *     static get template() {\n *       return html`\n *         <style>:host{ content:\"...\" }</style>\n *         <div class=\"shadowed\">${this.partialTemplate}</div>\n *         ${super.template}\n *       `;\n *     }\n *     static get partialTemplate() { return html`<span>Partial!</span>`; }\n *\n * @param {!ITemplateArray} strings Constant parts of tagged template literal\n * @param {...*} values Variable parts of tagged template literal\n * @return {!HTMLTemplateElement} Constructed HTMLTemplateElement\n */\nexport const html = function html(strings, ...values) {\n  assertValidTemplateStringParameters(strings, values);\n  const template =\n      /** @type {!HTMLTemplateElement} */ (document.createElement('template'));\n  let value = values.reduce(\n      (acc, v, idx) => acc + htmlValue(v) + strings[idx + 1], strings[0]);\n  if (policy) {\n    value = policy.createHTML(value);\n  }\n  template.innerHTML = value;\n  return template;\n};\n\n/**\n * @param {!ITemplateArray} strings Constant parts of tagged template literal\n * @param {!Array<*>} values Array of values from quasis\n */\nconst assertValidTemplateStringParameters = (strings, values) => {\n  // Note: if/when https://github.com/tc39/proposal-array-is-template-object\n  // is standardized, use that instead when available, as it can perform an\n  // unforgable check (though of course, the function itself can be forged).\n  if (!Array.isArray(strings) || !Array.isArray(strings.raw) ||\n      (values.length !== strings.length - 1)) {\n    // This is either caused by a browser bug, a compiler bug, or someone\n    // calling the html template tag function as a regular function.\n    //\n    throw new TypeError('Invalid call to the html template tag');\n  }\n};\n\n/**\n * An html literal tag that can be used with `html` to compose.\n * a literal string.\n *\n * Example:\n *\n *     static get template() {\n *       return html`\n *         <style>\n *           :host { display: block; }\n *           ${this.styleTemplate()}\n *         </style>\n *         <div class=\"shadowed\">${staticValue}</div>\n *         ${super.template}\n *       `;\n *     }\n *     static get styleTemplate() {\n *        return htmlLiteral`.shadowed { background: gray; }`;\n *     }\n *\n * @param {!ITemplateArray} strings Constant parts of tagged template literal\n * @param {...*} values Variable parts of tagged template literal\n * @return {!LiteralString} Constructed literal string\n */\nexport const htmlLiteral = function(strings, ...values) {\n  return new LiteralString(strings, values);\n};\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\nimport { ElementMixin, version } from './lib/mixins/element-mixin.js';\nexport { html } from './lib/utils/html-tag.js';\n\nexport { version };\n\n/**\n * Base class that provides the core API for Polymer's meta-programming\n * features including template stamping, data-binding, attribute deserialization,\n * and property change observation.\n *\n * @customElement\n * @polymer\n * @constructor\n * @implements {Polymer_ElementMixin}\n * @extends HTMLElement\n * @appliesMixin ElementMixin\n * @summary Custom element base class that provides the core API for Polymer's\n *   key meta-programming features including template stamping, data-binding,\n *   attribute deserialization, and property change observation\n */\nexport const PolymerElement = ElementMixin(HTMLElement);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * Array of Vaadin custom element classes that have been subscribed to the dir changes.\n */\nconst directionSubscribers = [];\n\nfunction alignDirs(element, documentDir, elementDir = element.getAttribute('dir')) {\n  if (documentDir) {\n    element.setAttribute('dir', documentDir);\n  } else if (elementDir != null) {\n    element.removeAttribute('dir');\n  }\n}\n\nfunction getDocumentDir() {\n  return document.documentElement.getAttribute('dir');\n}\n\nfunction directionUpdater() {\n  const documentDir = getDocumentDir();\n  directionSubscribers.forEach((element) => {\n    alignDirs(element, documentDir);\n  });\n}\n\nconst directionObserver = new MutationObserver(directionUpdater);\ndirectionObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['dir'] });\n\n/**\n * A mixin to handle `dir` attribute based on the one set on the `<html>` element.\n *\n * @polymerMixin\n */\nexport const DirMixin = (superClass) =>\n  class VaadinDirMixin extends superClass {\n    static get properties() {\n      return {\n        /**\n         * @protected\n         */\n        dir: {\n          type: String,\n          value: '',\n          reflectToAttribute: true,\n          converter: {\n            fromAttribute: (attr) => {\n              return !attr ? '' : attr;\n            },\n            toAttribute: (prop) => {\n              return prop === '' ? null : prop;\n            },\n          },\n        },\n      };\n    }\n\n    /**\n     * @return {boolean}\n     * @protected\n     */\n    get __isRTL() {\n      return this.getAttribute('dir') === 'rtl';\n    }\n\n    /** @protected */\n    connectedCallback() {\n      super.connectedCallback();\n\n      if (!this.hasAttribute('dir') || this.__restoreSubscription) {\n        this.__subscribe();\n        alignDirs(this, getDocumentDir(), null);\n      }\n    }\n\n    /** @protected */\n    attributeChangedCallback(name, oldValue, newValue) {\n      super.attributeChangedCallback(name, oldValue, newValue);\n      if (name !== 'dir') {\n        return;\n      }\n\n      const documentDir = getDocumentDir();\n\n      // New value equals to the document direction and the element is not subscribed to the changes\n      const newValueEqlDocDir = newValue === documentDir && directionSubscribers.indexOf(this) === -1;\n      // Value was emptied and the element is not subscribed to the changes\n      const newValueEmptied = !newValue && oldValue && directionSubscribers.indexOf(this) === -1;\n      // New value is different and the old equals to document direction and the element is not subscribed to the changes\n      const newDiffValue = newValue !== documentDir && oldValue === documentDir;\n\n      if (newValueEqlDocDir || newValueEmptied) {\n        this.__subscribe();\n        alignDirs(this, documentDir, newValue);\n      } else if (newDiffValue) {\n        this.__unsubscribe();\n      }\n    }\n\n    /** @protected */\n    disconnectedCallback() {\n      super.disconnectedCallback();\n      this.__restoreSubscription = directionSubscribers.includes(this);\n      this.__unsubscribe();\n    }\n\n    /** @protected */\n    _valueToNodeAttribute(node, value, attribute) {\n      // Override default Polymer attribute reflection to match native behavior of HTMLElement.dir property\n      // If the property contains an empty string then it should not create an empty attribute\n      if (attribute === 'dir' && value === '' && !node.hasAttribute('dir')) {\n        return;\n      }\n      super._valueToNodeAttribute(node, value, attribute);\n    }\n\n    /** @protected */\n    _attributeToProperty(attribute, value, type) {\n      // Override default Polymer attribute reflection to match native behavior of HTMLElement.dir property\n      // If the attribute is removed, then the dir property should contain an empty string instead of null\n      if (attribute === 'dir' && !value) {\n        this.dir = '';\n      } else {\n        super._attributeToProperty(attribute, value, type);\n      }\n    }\n\n    /** @private */\n    __subscribe() {\n      if (!directionSubscribers.includes(this)) {\n        directionSubscribers.push(this);\n      }\n    }\n\n    /** @private */\n    __unsubscribe() {\n      if (directionSubscribers.includes(this)) {\n        directionSubscribers.splice(directionSubscribers.indexOf(this), 1);\n      }\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { html, PolymerElement } from '@polymer/polymer';\nimport { DirMixin } from '@vaadin/component-base/src/dir-mixin.js';\nimport { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nexport class InputContainer extends ThemableMixin(DirMixin(PolymerElement)) {\n  static get is() {\n    return 'vaadin-input-container';\n  }\n\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: flex;\n          align-items: center;\n          flex: 0 1 auto;\n          border-radius:\n            /* See https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius */\n            var(--vaadin-input-field-top-start-radius, var(--__border-radius))\n            var(--vaadin-input-field-top-end-radius, var(--__border-radius))\n            var(--vaadin-input-field-bottom-end-radius, var(--__border-radius))\n            var(--vaadin-input-field-bottom-start-radius, var(--__border-radius));\n          --_border-radius: var(--vaadin-input-field-border-radius, 0px);\n          --_input-border-width: var(--vaadin-input-field-border-width, 0);\n          --_input-border-color: var(--vaadin-input-field-border-color, transparent);\n          box-shadow: inset 0 0 0 var(--_input-border-width, 0) var(--_input-border-color);\n        }\n\n        :host([dir='rtl']) {\n          border-radius:\n            /* Don't use logical props, see https://github.com/vaadin/vaadin-time-picker/issues/145 */\n            var(--vaadin-input-field-top-end-radius, var(--_border-radius))\n            var(--vaadin-input-field-top-start-radius, var(--_border-radius))\n            var(--vaadin-input-field-bottom-start-radius, var(--_border-radius))\n            var(--vaadin-input-field-bottom-end-radius, var(--_border-radius));\n        }\n\n        :host([hidden]) {\n          display: none !important;\n        }\n\n        /* Reset the native input styles */\n        ::slotted(input) {\n          -webkit-appearance: none;\n          -moz-appearance: none;\n          flex: auto;\n          white-space: nowrap;\n          overflow: hidden;\n          width: 100%;\n          height: 100%;\n          outline: none;\n          margin: 0;\n          padding: 0;\n          border: 0;\n          border-radius: 0;\n          min-width: 0;\n          font: inherit;\n          line-height: normal;\n          color: inherit;\n          background-color: transparent;\n          /* Disable default invalid style in Firefox */\n          box-shadow: none;\n        }\n\n        ::slotted(*) {\n          flex: none;\n        }\n\n        ::slotted(:is(input, textarea))::placeholder {\n          /* Use ::slotted(input:placeholder-shown) in themes to style the placeholder. */\n          /* because ::slotted(...)::placeholder does not work in Safari. */\n          font: inherit;\n          color: inherit;\n          /* Override default opacity in Firefox */\n          opacity: 1;\n        }\n      </style>\n      <slot name=\"prefix\"></slot>\n      <slot></slot>\n      <slot name=\"suffix\"></slot>\n    `;\n  }\n\n  static get properties() {\n    return {\n      /**\n       * If true, the user cannot interact with this element.\n       */\n      disabled: {\n        type: Boolean,\n        reflectToAttribute: true,\n      },\n\n      /**\n       * Set to true to make this element read-only.\n       */\n      readonly: {\n        type: Boolean,\n        reflectToAttribute: true,\n      },\n\n      /**\n       * Set to true when the element is invalid.\n       */\n      invalid: {\n        type: Boolean,\n        reflectToAttribute: true,\n      },\n    };\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n\n    this.addEventListener('pointerdown', (event) => {\n      if (event.target === this) {\n        // Prevent direct clicks to the input container from blurring the input\n        event.preventDefault();\n      }\n    });\n\n    this.addEventListener('click', (event) => {\n      if (event.target === this) {\n        // The vaadin-input-container element was directly clicked,\n        // focus any focusable child element from the default slot\n        this.shadowRoot\n          .querySelector('slot:not([name])')\n          .assignedNodes({ flatten: true })\n          .forEach((node) => node.focus && node.focus());\n      }\n    });\n  }\n}\n\ncustomElements.define(InputContainer.is, InputContainer);\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport './version.js';\nimport { css } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { addLumoGlobalStyles } from './global.js';\n\nconst spacing = css`\n  :host {\n    /* Square */\n    --lumo-space-xs: 0.25rem;\n    --lumo-space-s: 0.5rem;\n    --lumo-space-m: 1rem;\n    --lumo-space-l: 1.5rem;\n    --lumo-space-xl: 2.5rem;\n\n    /* Wide */\n    --lumo-space-wide-xs: calc(var(--lumo-space-xs) / 2) var(--lumo-space-xs);\n    --lumo-space-wide-s: calc(var(--lumo-space-s) / 2) var(--lumo-space-s);\n    --lumo-space-wide-m: calc(var(--lumo-space-m) / 2) var(--lumo-space-m);\n    --lumo-space-wide-l: calc(var(--lumo-space-l) / 2) var(--lumo-space-l);\n    --lumo-space-wide-xl: calc(var(--lumo-space-xl) / 2) var(--lumo-space-xl);\n\n    /* Tall */\n    --lumo-space-tall-xs: var(--lumo-space-xs) calc(var(--lumo-space-xs) / 2);\n    --lumo-space-tall-s: var(--lumo-space-s) calc(var(--lumo-space-s) / 2);\n    --lumo-space-tall-m: var(--lumo-space-m) calc(var(--lumo-space-m) / 2);\n    --lumo-space-tall-l: var(--lumo-space-l) calc(var(--lumo-space-l) / 2);\n    --lumo-space-tall-xl: var(--lumo-space-xl) calc(var(--lumo-space-xl) / 2);\n  }\n`;\n\naddLumoGlobalStyles('spacing-props', spacing);\n\nexport { spacing };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '../color.js';\nimport '../spacing.js';\nimport '../style.js';\nimport '../typography.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst overlay = css`\n  :host {\n    top: var(--lumo-space-m);\n    right: var(--lumo-space-m);\n    bottom: var(--lumo-space-m);\n    left: var(--lumo-space-m);\n    /* Workaround for Edge issue (only on Surface), where an overflowing vaadin-list-box inside vaadin-select-overlay makes the overlay transparent */\n    /* stylelint-disable-next-line */\n    outline: 0px solid transparent;\n  }\n\n  [part='overlay'] {\n    background-color: var(--lumo-base-color);\n    background-image: linear-gradient(var(--lumo-tint-5pct), var(--lumo-tint-5pct));\n    border-radius: var(--lumo-border-radius-m);\n    box-shadow: 0 0 0 1px var(--lumo-shade-5pct), var(--lumo-box-shadow-m);\n    color: var(--lumo-body-text-color);\n    font-family: var(--lumo-font-family);\n    font-size: var(--lumo-font-size-m);\n    font-weight: 400;\n    line-height: var(--lumo-line-height-m);\n    letter-spacing: 0;\n    text-transform: none;\n    -webkit-text-size-adjust: 100%;\n    -webkit-font-smoothing: antialiased;\n    -moz-osx-font-smoothing: grayscale;\n  }\n\n  [part='content'] {\n    padding: var(--lumo-space-xs);\n  }\n\n  [part='backdrop'] {\n    background-color: var(--lumo-shade-20pct);\n    animation: 0.2s lumo-overlay-backdrop-enter both;\n    will-change: opacity;\n  }\n\n  @keyframes lumo-overlay-backdrop-enter {\n    0% {\n      opacity: 0;\n    }\n  }\n\n  :host([closing]) [part='backdrop'] {\n    animation: 0.2s lumo-overlay-backdrop-exit both;\n  }\n\n  @keyframes lumo-overlay-backdrop-exit {\n    100% {\n      opacity: 0;\n    }\n  }\n\n  @keyframes lumo-overlay-dummy-animation {\n    0% {\n      opacity: 1;\n    }\n\n    100% {\n      opacity: 1;\n    }\n  }\n`;\n\nregisterStyles('', overlay, { moduleId: 'lumo-overlay' });\n\nexport { overlay };\n","import { overlay } from '@vaadin/vaadin-lumo-styles/mixins/overlay.js';\nimport { registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles('vaadin-overlay', overlay, { moduleId: 'lumo-vaadin-overlay' });\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\n/**\n * Module for scheduling flushable pre-render and post-render tasks.\n *\n * @summary Module for scheduling flushable pre-render and post-render tasks.\n */\n\nimport './boot.js';\n\nlet scheduled = false;\nlet beforeRenderQueue = [];\nlet afterRenderQueue = [];\n\nfunction schedule() {\n  scheduled = true;\n  // before next render\n  requestAnimationFrame(function() {\n    scheduled = false;\n    flushQueue(beforeRenderQueue);\n    // after the render\n    setTimeout(function() {\n      runQueue(afterRenderQueue);\n    });\n  });\n}\n\nfunction flushQueue(queue) {\n  while (queue.length) {\n    callMethod(queue.shift());\n  }\n}\n\nfunction runQueue(queue) {\n  for (let i=0, l=queue.length; i < l; i++) {\n    callMethod(queue.shift());\n  }\n}\n\nfunction callMethod(info) {\n  const context = info[0];\n  const callback = info[1];\n  const args = info[2];\n  try {\n    callback.apply(context, args);\n  } catch(e) {\n    setTimeout(() => {\n      throw e;\n    });\n  }\n}\n\n/**\n * Flushes all `beforeNextRender` tasks, followed by all `afterNextRender`\n * tasks.\n *\n * @return {void}\n */\nexport function flush() {\n  while (beforeRenderQueue.length || afterRenderQueue.length) {\n    flushQueue(beforeRenderQueue);\n    flushQueue(afterRenderQueue);\n  }\n  scheduled = false;\n}\n\n\n/**\n * Enqueues a callback which will be run before the next render, at\n * `requestAnimationFrame` timing.\n *\n * This method is useful for enqueuing work that requires DOM measurement,\n * since measurement may not be reliable in custom element callbacks before\n * the first render, as well as for batching measurement tasks in general.\n *\n * Tasks in this queue may be flushed by calling `flush()`.\n *\n * @param {*} context Context object the callback function will be bound to\n * @param {function(...*):void} callback Callback function\n * @param {!Array=} args An array of arguments to call the callback function with\n * @return {void}\n */\nexport function beforeNextRender(context, callback, args) {\n  if (!scheduled) {\n    schedule();\n  }\n  beforeRenderQueue.push([context, callback, args]);\n}\n\n/**\n * Enqueues a callback which will be run after the next render, equivalent\n * to one task (`setTimeout`) after the next `requestAnimationFrame`.\n *\n * This method is useful for tuning the first-render performance of an\n * element or application by deferring non-critical work until after the\n * first paint.  Typical non-render-critical work may include adding UI\n * event listeners and aria attributes.\n *\n * @param {*} context Context object the callback function will be bound to\n * @param {function(...*):void} callback Callback function\n * @param {!Array=} args An array of arguments to call the callback function with\n * @return {void}\n */\nexport function afterNextRender(context, callback, args) {\n  if (!scheduled) {\n    schedule();\n  }\n  afterRenderQueue.push([context, callback, args]);\n}\n\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\nconst testUserAgent = (regexp) => regexp.test(navigator.userAgent);\n\nconst testPlatform = (regexp) => regexp.test(navigator.platform);\n\nconst testVendor = (regexp) => regexp.test(navigator.vendor);\n\nexport const isAndroid = testUserAgent(/Android/u);\n\nexport const isChrome = testUserAgent(/Chrome/u) && testVendor(/Google Inc/u);\n\nexport const isFirefox = testUserAgent(/Firefox/u);\n\n// IPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support.\nexport const isIPad = testPlatform(/^iPad/u) || (testPlatform(/^Mac/u) && navigator.maxTouchPoints > 1);\n\nexport const isIPhone = testPlatform(/^iPhone/u);\n\nexport const isIOS = isIPhone || isIPad;\n\nexport const isSafari = testUserAgent(/^((?!chrome|android).)*safari/iu);\n\nexport const isTouch = (() => {\n  try {\n    document.createEvent('TouchEvent');\n    return true;\n  } catch (e) {\n    return false;\n  }\n})();\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * Passes the component to the template renderer callback if the template renderer is imported.\n * Otherwise, if there is a template, it warns that the template renderer needs to be imported.\n *\n * @param {HTMLElement} component\n */\nexport function processTemplates(component) {\n  if (window.Vaadin && window.Vaadin.templateRendererCallback) {\n    window.Vaadin.templateRendererCallback(component);\n    return;\n  }\n\n  if (component.querySelector('template')) {\n    console.warn(\n      `WARNING: <template> inside <${component.localName}> is no longer supported. Import @vaadin/polymer-legacy-adapter/template-renderer.js to enable compatibility.`,\n    );\n  }\n}\n","/**\n * @license\n * Copyright (c) 2017 Anton Korzunov\n * SPDX-License-Identifier: MIT\n */\n\n/**\n * @fileoverview\n *\n * This module includes JS code copied from the `aria-hidden` package:\n * https://github.com/theKashey/aria-hidden/blob/master/src/index.ts\n */\n\n/** @type {WeakMap<Element, number>} */\nlet counterMap = new WeakMap();\n\n/** @type {WeakMap<Element, boolean>} */\nlet uncontrolledNodes = new WeakMap();\n\n/** @type {Record<string, WeakMap<Element, number>>} */\nlet markerMap = {};\n\n/** @type {number} */\nlet lockCount = 0;\n\n/**\n * @param {Element | Shadow} node\n * @return {Element | null}\n */\nconst unwrapHost = (node) => (node ? node.host || unwrapHost(node.parentNode) : null);\n\n/**\n * @param {?Node} node\n * @return {boolean}\n */\nconst isElement = (node) => node && node.nodeType === Node.ELEMENT_NODE;\n\n/**\n * @param  {...unknown} args\n */\nconst logError = (...args) => {\n  console.error(`Error: ${args.join(' ')}. Skip setting aria-hidden.`);\n};\n\n/**\n * @param {HTMLElement} parent\n * @param {Element[]} targets\n * @return {Element[]}\n */\nconst correctTargets = (parent, targets) => {\n  if (!isElement(parent)) {\n    logError(parent, 'is not a valid element');\n    return [];\n  }\n\n  return targets\n    .map((target) => {\n      if (!isElement(target)) {\n        logError(target, 'is not a valid element');\n        return null;\n      }\n\n      if (parent.contains(target)) {\n        return target;\n      }\n\n      const correctedTarget = unwrapHost(target);\n      if (correctedTarget && parent.contains(correctedTarget)) {\n        return correctedTarget;\n      }\n\n      logError(target, 'is not contained inside', parent);\n      return null;\n    })\n    .filter((x) => Boolean(x));\n};\n\n/**\n * Marks everything except given node(or nodes) as aria-hidden\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param {HTMLElement} [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @param {String} [controlAttribute] - html Attribute to control\n * @return {Function}\n */\nconst applyAttributeToOthers = (originalTarget, parentNode, markerName, controlAttribute) => {\n  const targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]);\n\n  if (!markerMap[markerName]) {\n    markerMap[markerName] = new WeakMap();\n  }\n\n  const markerCounter = markerMap[markerName];\n\n  /** @type {Element[]} */\n  const hiddenNodes = [];\n\n  /** @type {Set<Node>} */\n  const elementsToKeep = new Set();\n\n  /** @type {Set<Node>} */\n  const elementsToStop = new Set(targets);\n\n  /**\n   * @param {?Node} el\n   */\n  const keep = (el) => {\n    if (!el || elementsToKeep.has(el)) {\n      return;\n    }\n\n    elementsToKeep.add(el);\n    keep(el.parentNode);\n  };\n\n  targets.forEach(keep);\n\n  /**\n   * @param {?Node} el\n   */\n  const deep = (parent) => {\n    if (!parent || elementsToStop.has(parent)) {\n      return;\n    }\n\n    [...parent.children].forEach((node) => {\n      // Skip elements that don't need to be hidden\n      if (['template', 'script', 'style'].includes(node.localName)) {\n        return;\n      }\n\n      if (elementsToKeep.has(node)) {\n        deep(node);\n      } else {\n        const attr = node.getAttribute(controlAttribute);\n        const alreadyHidden = attr !== null && attr !== 'false';\n        const counterValue = (counterMap.get(node) || 0) + 1;\n        const markerValue = (markerCounter.get(node) || 0) + 1;\n\n        counterMap.set(node, counterValue);\n        markerCounter.set(node, markerValue);\n        hiddenNodes.push(node);\n\n        if (counterValue === 1 && alreadyHidden) {\n          uncontrolledNodes.set(node, true);\n        }\n\n        if (markerValue === 1) {\n          node.setAttribute(markerName, 'true');\n        }\n\n        if (!alreadyHidden) {\n          node.setAttribute(controlAttribute, 'true');\n        }\n      }\n    });\n  };\n\n  deep(parentNode);\n\n  elementsToKeep.clear();\n\n  lockCount += 1;\n\n  return () => {\n    hiddenNodes.forEach((node) => {\n      const counterValue = counterMap.get(node) - 1;\n      const markerValue = markerCounter.get(node) - 1;\n\n      counterMap.set(node, counterValue);\n      markerCounter.set(node, markerValue);\n\n      if (!counterValue) {\n        if (uncontrolledNodes.has(node)) {\n          uncontrolledNodes.delete(node);\n        } else {\n          node.removeAttribute(controlAttribute);\n        }\n      }\n\n      if (!markerValue) {\n        node.removeAttribute(markerName);\n      }\n    });\n\n    lockCount -= 1;\n\n    if (!lockCount) {\n      // clear\n      counterMap = new WeakMap();\n      counterMap = new WeakMap();\n      uncontrolledNodes = new WeakMap();\n      markerMap = {};\n    }\n  };\n};\n\n/**\n * Marks everything except given node(or nodes) as aria-hidden\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param {HTMLElement} [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Function} undo command\n */\nexport const hideOthers = (originalTarget, parentNode = document.body, markerName = 'data-aria-hidden') => {\n  const targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]);\n\n  if (parentNode) {\n    // We should not hide ariaLive elements - https://github.com/theKashey/aria-hidden/issues/10\n    targets.push(...Array.from(parentNode.querySelectorAll('[aria-live]')));\n  }\n\n  return applyAttributeToOthers(targets, parentNode, markerName, 'aria-hidden');\n};\n\n/**\n * Marks everything except given node(or nodes) as inert\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param {HTMLElement} [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Function} undo command\n */\nexport const inertOthers = (originalTarget, parentNode = document.body, markerName = 'data-inert-ed') => {\n  return applyAttributeToOthers(originalTarget, parentNode, markerName, 'inert');\n};\n\n/**\n * @return if current browser supports inert\n */\nexport const supportsInert = 'inert' in HTMLElement.prototype;\n\n/**\n * Automatic function to \"suppress\" DOM elements - _hide_ or _inert_ in the best possible way\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param {HTMLElement} [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Function} undo command\n */\nexport const suppressOthers = (originalTarget, parentNode, markerName) =>\n  (supportsInert ? inertOthers : hideOthers)(originalTarget, parentNode, markerName);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { hideOthers } from './aria-hidden.js';\n\n/**\n * A controller for handling modal state on the elements with `dialog` and `alertdialog` role.\n * See https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-modal\n *\n * Note, the actual `role` and `aria-modal` attributes are supposed to be handled by the\n * consumer web component. This is done in to ensure the controller only does one thing.\n */\nexport class AriaModalController {\n  /**\n   * @param {HTMLElement} host\n   */\n  constructor(host, callback) {\n    /**\n     * The controller host element.\n     *\n     * @type {HTMLElement}\n     */\n    this.host = host;\n\n    /**\n     * The callback used to detect which element\n     * to use as a target. Defaults to the host.\n     *\n     * @type {Function}\n     */\n    this.callback = typeof callback === 'function' ? callback : () => host;\n  }\n\n  /**\n   * Make the controller host modal by hiding other elements from screen readers\n   * using `aria-hidden` attribute (can be replaced with `inert` in the future).\n   *\n   * The method name is chosen to align with the one provided by native `<dialog>`:\n   * https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal\n   */\n  showModal() {\n    const targets = this.callback();\n    this.__showOthers = hideOthers(targets);\n  }\n\n  /**\n   * Remove `aria-hidden` from other elements unless there are any other\n   * controller hosts on the page activated by using `showModal()` call.\n   */\n  close() {\n    if (this.__showOthers) {\n      this.__showOthers();\n      this.__showOthers = null;\n    }\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n// We consider the keyboard to be active if the window has received a keydown\n// event since the last mousedown event.\nlet keyboardActive = false;\n\n// Listen for top-level keydown and mousedown events.\n// Use capture phase so we detect events even if they're handled.\nwindow.addEventListener(\n  'keydown',\n  () => {\n    keyboardActive = true;\n  },\n  { capture: true },\n);\n\nwindow.addEventListener(\n  'mousedown',\n  () => {\n    keyboardActive = false;\n  },\n  { capture: true },\n);\n\n/**\n * Returns the actually focused element by traversing shadow\n * trees recursively to ensure it's the leaf element.\n *\n * @return {Element}\n */\nexport function getDeepActiveElement() {\n  let host = document.activeElement || document.body;\n  while (host.shadowRoot && host.shadowRoot.activeElement) {\n    host = host.shadowRoot.activeElement;\n  }\n  return host;\n}\n\n/**\n * Returns true if the window has received a keydown\n * event since the last mousedown event.\n *\n * @return {boolean}\n */\nexport function isKeyboardActive() {\n  return keyboardActive;\n}\n\n/**\n * Returns true if the element is hidden directly with `display: none` or `visibility: hidden`,\n * false otherwise.\n *\n * The method doesn't traverse the element's ancestors, it only checks for the CSS properties\n * set directly to or inherited by the element.\n *\n * @param {HTMLElement} element\n * @return {boolean}\n */\nfunction isElementHiddenDirectly(element) {\n  // Check inline style first to save a re-flow.\n  const style = element.style;\n  if (style.visibility === 'hidden' || style.display === 'none') {\n    return true;\n  }\n\n  const computedStyle = window.getComputedStyle(element);\n  if (computedStyle.visibility === 'hidden' || computedStyle.display === 'none') {\n    return true;\n  }\n\n  return false;\n}\n\n/**\n * Returns if element `a` has lower tab order compared to element `b`\n * (both elements are assumed to be focusable and tabbable).\n * Elements with tabindex = 0 have lower tab order compared to elements\n * with tabindex > 0.\n * If both have same tabindex, it returns false.\n *\n * @param {HTMLElement} a\n * @param {HTMLElement} b\n * @return {boolean}\n */\nfunction hasLowerTabOrder(a, b) {\n  // Normalize tabIndexes\n  // e.g. in Firefox `<div contenteditable>` has `tabIndex = -1`\n  const ati = Math.max(a.tabIndex, 0);\n  const bti = Math.max(b.tabIndex, 0);\n  return ati === 0 || bti === 0 ? bti > ati : ati > bti;\n}\n\n/**\n * Merge sort iterator, merges the two arrays into one, sorted by tabindex.\n *\n * @param {HTMLElement[]} left\n * @param {HTMLElement[]} right\n * @return {HTMLElement[]}\n */\nfunction mergeSortByTabIndex(left, right) {\n  const result = [];\n  while (left.length > 0 && right.length > 0) {\n    if (hasLowerTabOrder(left[0], right[0])) {\n      result.push(right.shift());\n    } else {\n      result.push(left.shift());\n    }\n  }\n\n  return result.concat(left, right);\n}\n\n/**\n * Sorts an array of elements by tabindex. Returns a new array.\n *\n * @param {HTMLElement[]} elements\n * @return {HTMLElement[]}\n */\nfunction sortElementsByTabIndex(elements) {\n  // Implement a merge sort as Array.prototype.sort does a non-stable sort\n  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\n  const len = elements.length;\n  if (len < 2) {\n    return elements;\n  }\n  const pivot = Math.ceil(len / 2);\n  const left = sortElementsByTabIndex(elements.slice(0, pivot));\n  const right = sortElementsByTabIndex(elements.slice(pivot));\n\n  return mergeSortByTabIndex(left, right);\n}\n\n/**\n * Returns true if the element is hidden, false otherwise.\n *\n * An element is treated as hidden when any of the following conditions are met:\n * - the element itself or one of its ancestors has `display: none`.\n * - the element has or inherits `visibility: hidden`.\n *\n * @param {HTMLElement} element\n * @return {boolean}\n */\nexport function isElementHidden(element) {\n  // `offsetParent` is `null` when the element itself\n  // or one of its ancestors is hidden with `display: none`.\n  // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent\n  // However `offsetParent` is also null when the element is using fixed\n  // positioning, so additionally check if the element takes up layout space.\n  if (element.offsetParent === null && element.clientWidth === 0 && element.clientHeight === 0) {\n    return true;\n  }\n\n  return isElementHiddenDirectly(element);\n}\n\n/**\n * Returns true if the element is focusable, otherwise false.\n *\n * The list of focusable elements is taken from http://stackoverflow.com/a/1600194/4228703.\n * However, there isn't a definite list, it's up to the browser.\n * The only standard we have is DOM Level 2 HTML https://www.w3.org/TR/DOM-Level-2-HTML/html.html,\n * according to which the only elements that have a `focus()` method are:\n * - HTMLInputElement\n * - HTMLSelectElement\n * - HTMLTextAreaElement\n * - HTMLAnchorElement\n *\n * This notably omits HTMLButtonElement and HTMLAreaElement.\n * Referring to these tests with tabbables in different browsers\n * http://allyjs.io/data-tables/focusable.html\n *\n * @param {HTMLElement} element\n * @return {boolean}\n */\nexport function isElementFocusable(element) {\n  // The element cannot be focused if its `tabindex` attribute is set to `-1`.\n  if (element.matches('[tabindex=\"-1\"]')) {\n    return false;\n  }\n\n  // Elements that cannot be focused if they have a `disabled` attribute.\n  if (element.matches('input, select, textarea, button, object')) {\n    return element.matches(':not([disabled])');\n  }\n\n  // Elements that can be focused even if they have a `disabled` attribute.\n  return element.matches('a[href], area[href], iframe, [tabindex], [contentEditable]');\n}\n\n/**\n * Returns true if the element is focused, false otherwise.\n *\n * @param {HTMLElement} element\n * @return {boolean}\n */\nexport function isElementFocused(element) {\n  return element.getRootNode().activeElement === element;\n}\n\n/**\n * Returns the normalized element tabindex. If not focusable, returns -1.\n * It checks for the attribute \"tabindex\" instead of the element property\n * `tabIndex` since browsers assign different values to it.\n * e.g. in Firefox `<div contenteditable>` has `tabIndex = -1`\n *\n * @param {HTMLElement} element\n * @return {number}\n */\nfunction normalizeTabIndex(element) {\n  if (!isElementFocusable(element)) {\n    return -1;\n  }\n\n  const tabIndex = element.getAttribute('tabindex') || 0;\n  return Number(tabIndex);\n}\n\n/**\n * Searches for nodes that are tabbable and adds them to the `result` array.\n * Returns if the `result` array needs to be sorted by tabindex.\n *\n * @param {Node} node The starting point for the search; added to `result` if tabbable.\n * @param {HTMLElement[]} result\n * @return {boolean}\n * @private\n */\nfunction collectFocusableNodes(node, result) {\n  if (node.nodeType !== Node.ELEMENT_NODE || isElementHiddenDirectly(node)) {\n    // Don't traverse children if the node is not an HTML element or not visible.\n    return false;\n  }\n\n  const element = /** @type {HTMLElement} */ (node);\n  const tabIndex = normalizeTabIndex(element);\n  let needsSort = tabIndex > 0;\n  if (tabIndex >= 0) {\n    result.push(element);\n  }\n\n  let children = [];\n  if (element.localName === 'slot') {\n    children = element.assignedNodes({ flatten: true });\n  } else {\n    // Use shadow root if possible, will check for distributed nodes.\n    children = (element.shadowRoot || element).children;\n  }\n  [...children].forEach((child) => {\n    // Ensure method is always invoked to collect focusable children.\n    needsSort = collectFocusableNodes(child, result) || needsSort;\n  });\n  return needsSort;\n}\n\n/**\n * Returns a tab-ordered array of focusable elements for a root element.\n * The resulting array will include the root element if it is focusable.\n *\n * The method traverses nodes in shadow DOM trees too if any.\n *\n * @param {HTMLElement} element\n * @return {HTMLElement[]}\n */\nexport function getFocusableElements(element) {\n  const focusableElements = [];\n  const needsSortByTabIndex = collectFocusableNodes(element, focusableElements);\n  // If there is at least one element with tabindex > 0,\n  // we need to sort the final array by tabindex.\n  if (needsSortByTabIndex) {\n    return sortElementsByTabIndex(focusableElements);\n  }\n  return focusableElements;\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { getDeepActiveElement } from './focus-utils.js';\n\n/**\n * A controller for saving a focused node and restoring focus to it later.\n */\nexport class FocusRestorationController {\n  /**\n   * Saves the given node as a target for restoring focus to\n   * when `restoreFocus()` is called. If no node is provided,\n   * the currently focused node in the DOM is saved as a target.\n   *\n   * @param {Node | null | undefined} focusNode\n   */\n  saveFocus(focusNode) {\n    this.focusNode = focusNode || getDeepActiveElement();\n  }\n\n  /**\n   * Restores focus to the target node that was saved previously with `saveFocus()`.\n   */\n  restoreFocus() {\n    const focusNode = this.focusNode;\n    if (!focusNode) {\n      return;\n    }\n\n    if (getDeepActiveElement() === document.body) {\n      // In Firefox and Safari, focusing the node synchronously\n      // doesn't work as expected when the overlay is closing on outside click.\n      // These browsers force focus to move to the body element and retain it\n      // there until the next event loop iteration.\n      setTimeout(() => focusNode.focus());\n    } else {\n      focusNode.focus();\n    }\n\n    this.focusNode = null;\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { getFocusableElements, isElementFocused } from './focus-utils.js';\n\nconst instances = [];\n\n/**\n * A controller for trapping focus within a DOM node.\n */\nexport class FocusTrapController {\n  /**\n   * @param {HTMLElement} host\n   */\n  constructor(host) {\n    /**\n     * The controller host element.\n     *\n     * @type {HTMLElement}\n     */\n    this.host = host;\n\n    /**\n     * A node for trapping focus in.\n     *\n     * @type {HTMLElement | null}\n     * @private\n     */\n    this.__trapNode = null;\n\n    this.__onKeyDown = this.__onKeyDown.bind(this);\n  }\n\n  /**\n   * An array of tab-ordered focusable elements inside the trap node.\n   *\n   * @return {HTMLElement[]}\n   * @private\n   */\n  get __focusableElements() {\n    return getFocusableElements(this.__trapNode);\n  }\n\n  /**\n   * The index of the element inside the trap node that currently has focus.\n   *\n   * @return {HTMLElement | undefined}\n   * @private\n   */\n  get __focusedElementIndex() {\n    const focusableElements = this.__focusableElements;\n    return focusableElements.indexOf(focusableElements.filter(isElementFocused).pop());\n  }\n\n  hostConnected() {\n    document.addEventListener('keydown', this.__onKeyDown);\n  }\n\n  hostDisconnected() {\n    document.removeEventListener('keydown', this.__onKeyDown);\n  }\n\n  /**\n   * Activates a focus trap for a DOM node that will prevent focus from escaping the node.\n   * The trap can be deactivated with the `.releaseFocus()` method.\n   *\n   * If focus is initially outside the trap, the method will move focus inside,\n   * on the first focusable element of the trap in the tab order.\n   * The first focusable element can be the trap node itself if it is focusable\n   * and comes first in the tab order.\n   *\n   * If there are no focusable elements, the method will throw an exception\n   * and the trap will not be set.\n   *\n   * @param {HTMLElement} trapNode\n   */\n  trapFocus(trapNode) {\n    this.__trapNode = trapNode;\n\n    if (this.__focusableElements.length === 0) {\n      this.__trapNode = null;\n      throw new Error('The trap node should have at least one focusable descendant or be focusable itself.');\n    }\n\n    instances.push(this);\n\n    if (this.__focusedElementIndex === -1) {\n      this.__focusableElements[0].focus();\n    }\n  }\n\n  /**\n   * Deactivates the focus trap set with the `.trapFocus()` method\n   * so that it becomes possible to tab outside the trap node.\n   */\n  releaseFocus() {\n    this.__trapNode = null;\n\n    instances.pop();\n  }\n\n  /**\n   * A `keydown` event handler that manages tabbing navigation when the trap is enabled.\n   *\n   * - Moves focus to the next focusable element of the trap on `Tab` press.\n   * When no next element to focus, the method moves focus to the first focusable element.\n   * - Moves focus to the prev focusable element of the trap on `Shift+Tab` press.\n   * When no prev element to focus, the method moves focus to the last focusable element.\n   *\n   * @param {KeyboardEvent} event\n   * @private\n   */\n  __onKeyDown(event) {\n    if (!this.__trapNode) {\n      return;\n    }\n\n    // Only handle events for the last instance\n    if (this !== Array.from(instances).pop()) {\n      return;\n    }\n\n    if (event.key === 'Tab') {\n      event.preventDefault();\n\n      const backward = event.shiftKey;\n      this.__focusNextElement(backward);\n    }\n  }\n\n  /**\n   * - Moves focus to the next focusable element if `backward === false`.\n   * When no next element to focus, the method moves focus to the first focusable element.\n   * - Moves focus to the prev focusable element if `backward === true`.\n   * When no prev element to focus the method moves focus to the last focusable element.\n   *\n   * If no focusable elements, the method returns immediately.\n   *\n   * @param {boolean} backward\n   * @private\n   */\n  __focusNextElement(backward = false) {\n    const focusableElements = this.__focusableElements;\n    const step = backward ? -1 : 1;\n    const currentIndex = this.__focusedElementIndex;\n    const nextIndex = (focusableElements.length + currentIndex + step) % focusableElements.length;\n    const element = focusableElements[nextIndex];\n    element.focus();\n    if (element.localName === 'input') {\n      element.select();\n    }\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\n\n/**\n * @typedef ReactiveController\n * @type {import('lit').ReactiveController}\n */\n\n/**\n * A mixin for connecting controllers to the element.\n *\n * @polymerMixin\n */\nexport const ControllerMixin = dedupingMixin(\n  (superClass) =>\n    class ControllerMixinClass extends superClass {\n      constructor() {\n        super();\n\n        /**\n         * @type {Set<ReactiveController>}\n         */\n        this.__controllers = new Set();\n      }\n\n      /** @protected */\n      connectedCallback() {\n        super.connectedCallback();\n\n        this.__controllers.forEach((c) => {\n          if (c.hostConnected) {\n            c.hostConnected();\n          }\n        });\n      }\n\n      /** @protected */\n      disconnectedCallback() {\n        super.disconnectedCallback();\n\n        this.__controllers.forEach((c) => {\n          if (c.hostDisconnected) {\n            c.hostDisconnected();\n          }\n        });\n      }\n\n      /**\n       * Registers a controller to participate in the element update cycle.\n       *\n       * @param {ReactiveController} controller\n       * @protected\n       */\n      addController(controller) {\n        this.__controllers.add(controller);\n        // Call hostConnected if a controller is added after the element is attached.\n        if (this.$ !== undefined && this.isConnected && controller.hostConnected) {\n          controller.hostConnected();\n        }\n      }\n\n      /**\n       * Removes a controller from the element.\n       *\n       * @param {ReactiveController} controller\n       * @protected\n       */\n      removeController(controller) {\n        this.__controllers.delete(controller);\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { AriaModalController } from '@vaadin/a11y-base/src/aria-modal-controller.js';\nimport { FocusRestorationController } from '@vaadin/a11y-base/src/focus-restoration-controller.js';\nimport { FocusTrapController } from '@vaadin/a11y-base/src/focus-trap-controller.js';\nimport { getDeepActiveElement } from '@vaadin/a11y-base/src/focus-utils.js';\nimport { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';\n\n/**\n * @polymerMixin\n * @mixes ControllerMixin\n */\nexport const OverlayFocusMixin = (superClass) =>\n  class OverlayFocusMixin extends ControllerMixin(superClass) {\n    static get properties() {\n      return {\n        /**\n         * When true, opening the overlay moves focus to the first focusable child,\n         * or to the overlay part with tabindex if there are no focusable children.\n         * @attr {boolean} focus-trap\n         */\n        focusTrap: {\n          type: Boolean,\n          value: false,\n        },\n\n        /**\n         * Set to true to enable restoring of focus when overlay is closed.\n         * @attr {boolean} restore-focus-on-close\n         */\n        restoreFocusOnClose: {\n          type: Boolean,\n          value: false,\n        },\n\n        /**\n         * Set to specify the element which should be focused on overlay close,\n         * if `restoreFocusOnClose` is set to true.\n         * @type {HTMLElement}\n         */\n        restoreFocusNode: {\n          type: HTMLElement,\n        },\n      };\n    }\n\n    constructor() {\n      super();\n\n      this.__ariaModalController = new AriaModalController(this);\n      this.__focusTrapController = new FocusTrapController(this);\n      this.__focusRestorationController = new FocusRestorationController();\n    }\n\n    /** @protected */\n    ready() {\n      super.ready();\n\n      this.addController(this.__ariaModalController);\n      this.addController(this.__focusTrapController);\n      this.addController(this.__focusRestorationController);\n    }\n\n    /**\n     * Release focus and restore focus after the overlay is closed.\n     *\n     * @protected\n     */\n    _resetFocus() {\n      if (this.focusTrap) {\n        this.__ariaModalController.close();\n        this.__focusTrapController.releaseFocus();\n      }\n\n      if (this.restoreFocusOnClose && this._shouldRestoreFocus()) {\n        this.__focusRestorationController.restoreFocus();\n      }\n    }\n\n    /**\n     * Save the previously focused node when the overlay starts to open.\n     *\n     * @protected\n     */\n    _saveFocus() {\n      if (this.restoreFocusOnClose) {\n        this.__focusRestorationController.saveFocus(this.restoreFocusNode);\n      }\n    }\n\n    /**\n     * Trap focus within the overlay after opening has completed.\n     *\n     * @protected\n     */\n    _trapFocus() {\n      if (this.focusTrap) {\n        this.__ariaModalController.showModal();\n        this.__focusTrapController.trapFocus(this.$.overlay);\n      }\n    }\n\n    /**\n     * Returns true if focus is still inside the overlay or on the body element,\n     * otherwise false.\n     *\n     * Focus shouldn't be restored if it's been moved elsewhere by another\n     * component or as a result of a user interaction e.g. the user clicked\n     * on a button outside the overlay while the overlay was open.\n     *\n     * @protected\n     * @return {boolean}\n     */\n    _shouldRestoreFocus() {\n      const activeElement = getDeepActiveElement();\n      return activeElement === document.body || this._deepContains(activeElement);\n    }\n\n    /**\n     * Returns true if the overlay contains the given node,\n     * including those within shadow DOM trees.\n     *\n     * @param {Node} node\n     * @return {boolean}\n     * @protected\n     */\n    _deepContains(node) {\n      if (this.contains(node)) {\n        return true;\n      }\n      let n = node;\n      const doc = node.ownerDocument;\n      // Walk from node to `this` or `document`\n      while (n && n !== doc && n !== this) {\n        n = n.parentNode || n.host;\n      }\n      return n === this;\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { afterNextRender } from '@polymer/polymer/lib/utils/render-status.js';\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { isIOS } from '@vaadin/component-base/src/browser-utils.js';\nimport { DirMixin } from '@vaadin/component-base/src/dir-mixin.js';\nimport { processTemplates } from '@vaadin/component-base/src/templates.js';\nimport { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { OverlayFocusMixin } from './vaadin-overlay-focus-mixin.js';\n\n/**\n * `<vaadin-overlay>` is a Web Component for creating overlays. The content of the overlay\n * can be populated imperatively by using `renderer` callback function.\n *\n * ### Rendering\n *\n * The renderer function provides `root`, `owner`, `model` arguments when applicable.\n * Generate DOM content by using `model` object properties if needed, append it to the `root`\n * element and control the state of the host element by accessing `owner`. Before generating new\n * content, users are able to check if there is already content in `root` for reusing it.\n *\n * ```html\n * <vaadin-overlay id=\"overlay\"></vaadin-overlay>\n * ```\n * ```js\n * const overlay = document.querySelector('#overlay');\n * overlay.renderer = function(root) {\n *  root.textContent = \"Overlay content\";\n * };\n * ```\n *\n * Renderer is called on the opening of the overlay and each time the related model is updated.\n * DOM generated during the renderer call can be reused\n * in the next renderer call and will be provided with the `root` argument.\n * On first call it will be empty.\n *\n * ### Styling\n *\n * The following Shadow DOM parts are available for styling:\n *\n * Part name  | Description\n * -----------|---------------------------------------------------------|\n * `backdrop` | Backdrop of the overlay\n * `overlay`  | Container for position/sizing/alignment of the content\n * `content`  | Content of the overlay\n *\n * The following state attributes are available for styling:\n *\n * Attribute | Description | Part\n * ---|---|---\n * `opening` | Applied just after the overlay is attached to the DOM. You can apply a CSS @keyframe animation for this state. | `:host`\n * `closing` | Applied just before the overlay is detached from the DOM. You can apply a CSS @keyframe animation for this state. | `:host`\n *\n * The following custom CSS properties are available for styling:\n *\n * Custom CSS property | Description | Default value\n * ---|---|---\n * `--vaadin-overlay-viewport-bottom` | Bottom offset of the visible viewport area | `0` or detected offset\n *\n * See [Styling Components](https://vaadin.com/docs/latest/styling/styling-components) documentation.\n *\n * @fires {CustomEvent} opened-changed - Fired when the `opened` property changes.\n * @fires {CustomEvent} vaadin-overlay-open - Fired after the overlay is opened.\n * @fires {CustomEvent} vaadin-overlay-close - Fired when the opened overlay is about to be closed. Calling `preventDefault()` on the event cancels the closing.\n * @fires {CustomEvent} vaadin-overlay-closing - Fired when the overlay starts to close. Closing the overlay can be asynchronous depending on the animation.\n * @fires {CustomEvent} vaadin-overlay-closed - Fired after the overlay is closed.\n * @fires {CustomEvent} vaadin-overlay-outside-click - Fired before the overlay is closed on outside click. Calling `preventDefault()` on the event cancels the closing.\n * @fires {CustomEvent} vaadin-overlay-escape-press - Fired before the overlay is closed on Escape key press. Calling `preventDefault()` on the event cancels the closing.\n *\n * @extends HTMLElement\n * @mixes ThemableMixin\n * @mixes DirMixin\n * @mixes OverlayFocusMixin\n */\nclass Overlay extends OverlayFocusMixin(ThemableMixin(DirMixin(PolymerElement))) {\n  static get template() {\n    return html`\n      <style>\n        :host {\n          z-index: 200;\n          position: fixed;\n\n          /* Despite of what the names say, <vaadin-overlay> is just a container\n          for position/sizing/alignment. The actual overlay is the overlay part. */\n\n          /* Default position constraints: the entire viewport. Note: themes can\n          override this to introduce gaps between the overlay and the viewport. */\n          top: 0;\n          right: 0;\n          bottom: var(--vaadin-overlay-viewport-bottom);\n          left: 0;\n\n          /* Use flexbox alignment for the overlay part. */\n          display: flex;\n          flex-direction: column; /* makes dropdowns sizing easier */\n          /* Align to center by default. */\n          align-items: center;\n          justify-content: center;\n\n          /* Allow centering when max-width/max-height applies. */\n          margin: auto;\n\n          /* The host is not clickable, only the overlay part is. */\n          pointer-events: none;\n\n          /* Remove tap highlight on touch devices. */\n          -webkit-tap-highlight-color: transparent;\n\n          /* CSS API for host */\n          --vaadin-overlay-viewport-bottom: 0;\n        }\n\n        :host([hidden]),\n        :host(:not([opened]):not([closing])) {\n          display: none !important;\n        }\n\n        [part='overlay'] {\n          -webkit-overflow-scrolling: touch;\n          overflow: auto;\n          pointer-events: auto;\n\n          /* Prevent overflowing the host in MSIE 11 */\n          max-width: 100%;\n          box-sizing: border-box;\n\n          -webkit-tap-highlight-color: initial; /* reenable tap highlight inside */\n        }\n\n        [part='backdrop'] {\n          z-index: -1;\n          content: '';\n          background: rgba(0, 0, 0, 0.5);\n          position: fixed;\n          top: 0;\n          left: 0;\n          bottom: 0;\n          right: 0;\n          pointer-events: auto;\n        }\n      </style>\n\n      <div id=\"backdrop\" part=\"backdrop\" hidden$=\"[[!withBackdrop]]\"></div>\n      <div part=\"overlay\" id=\"overlay\" tabindex=\"0\">\n        <div part=\"content\" id=\"content\">\n          <slot></slot>\n        </div>\n      </div>\n    `;\n  }\n\n  static get is() {\n    return 'vaadin-overlay';\n  }\n\n  static get properties() {\n    return {\n      /**\n       * When true, the overlay is visible and attached to body.\n       */\n      opened: {\n        type: Boolean,\n        notify: true,\n        observer: '_openedChanged',\n        reflectToAttribute: true,\n      },\n\n      /**\n       * Owner element passed with renderer function\n       * @type {HTMLElement}\n       */\n      owner: Element,\n\n      /**\n       * Custom function for rendering the content of the overlay.\n       * Receives three arguments:\n       *\n       * - `root` The root container DOM element. Append your content to it.\n       * - `owner` The host element of the renderer function.\n       * - `model` The object with the properties related with rendering.\n       * @type {OverlayRenderer | null | undefined}\n       */\n      renderer: Function,\n\n      /**\n       * When true the overlay has backdrop on top of content when opened.\n       * @type {boolean}\n       */\n      withBackdrop: {\n        type: Boolean,\n        value: false,\n        reflectToAttribute: true,\n      },\n\n      /**\n       * Object with properties that is passed to `renderer` function\n       */\n      model: Object,\n\n      /**\n       * When true the overlay won't disable the main content, showing\n       * it doesn't change the functionality of the user interface.\n       * @type {boolean}\n       */\n      modeless: {\n        type: Boolean,\n        value: false,\n        reflectToAttribute: true,\n        observer: '_modelessChanged',\n      },\n\n      /**\n       * When set to true, the overlay is hidden. This also closes the overlay\n       * immediately in case there is a closing animation in progress.\n       * @type {boolean}\n       */\n      hidden: {\n        type: Boolean,\n        reflectToAttribute: true,\n        observer: '_hiddenChanged',\n      },\n\n      /** @private */\n      _mouseDownInside: {\n        type: Boolean,\n      },\n\n      /** @private */\n      _mouseUpInside: {\n        type: Boolean,\n      },\n\n      /** @private */\n      _oldOwner: Element,\n\n      /** @private */\n      _oldModel: Object,\n\n      /** @private */\n      _oldRenderer: Object,\n\n      /** @private */\n      _oldOpened: Boolean,\n    };\n  }\n\n  static get observers() {\n    return ['_rendererOrDataChanged(renderer, owner, model, opened)'];\n  }\n\n  /**\n   * Returns all attached overlays in visual stacking order.\n   * @private\n   */\n  static get __attachedInstances() {\n    return Array.from(document.body.children)\n      .filter((el) => el instanceof Overlay && !el.hasAttribute('closing'))\n      .sort((a, b) => a.__zIndex - b.__zIndex || 0);\n  }\n\n  constructor() {\n    super();\n    this._boundMouseDownListener = this._mouseDownListener.bind(this);\n    this._boundMouseUpListener = this._mouseUpListener.bind(this);\n    this._boundOutsideClickListener = this._outsideClickListener.bind(this);\n    this._boundKeydownListener = this._keydownListener.bind(this);\n\n    /* c8 ignore next 3 */\n    if (isIOS) {\n      this._boundIosResizeListener = () => this._detectIosNavbar();\n    }\n  }\n\n  /**\n   * Returns true if this is the last one in the opened overlays stack\n   * @return {boolean}\n   * @protected\n   */\n  get _last() {\n    return this === Overlay.__attachedInstances.pop();\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n\n    // Need to add dummy click listeners to this and the backdrop or else\n    // the document click event listener (_outsideClickListener) may never\n    // get invoked on iOS Safari (reproducible in <vaadin-dialog>\n    // and <vaadin-context-menu>).\n    this.addEventListener('click', () => {});\n    this.$.backdrop.addEventListener('click', () => {});\n\n    processTemplates(this);\n  }\n\n  /** @private */\n  _detectIosNavbar() {\n    /* c8 ignore next 15 */\n    if (!this.opened) {\n      return;\n    }\n\n    const innerHeight = window.innerHeight;\n    const innerWidth = window.innerWidth;\n\n    const landscape = innerWidth > innerHeight;\n\n    const clientHeight = document.documentElement.clientHeight;\n\n    if (landscape && clientHeight > innerHeight) {\n      this.style.setProperty('--vaadin-overlay-viewport-bottom', `${clientHeight - innerHeight}px`);\n    } else {\n      this.style.setProperty('--vaadin-overlay-viewport-bottom', '0');\n    }\n  }\n\n  /**\n   * @param {Event=} sourceEvent\n   */\n  close(sourceEvent) {\n    const evt = new CustomEvent('vaadin-overlay-close', {\n      bubbles: true,\n      cancelable: true,\n      detail: { sourceEvent },\n    });\n    this.dispatchEvent(evt);\n    if (!evt.defaultPrevented) {\n      this.opened = false;\n    }\n  }\n\n  /** @protected */\n  connectedCallback() {\n    super.connectedCallback();\n\n    /* c8 ignore next 3 */\n    if (this._boundIosResizeListener) {\n      this._detectIosNavbar();\n      window.addEventListener('resize', this._boundIosResizeListener);\n    }\n  }\n\n  /** @protected */\n  disconnectedCallback() {\n    super.disconnectedCallback();\n\n    /* c8 ignore next 3 */\n    if (this._boundIosResizeListener) {\n      window.removeEventListener('resize', this._boundIosResizeListener);\n    }\n  }\n\n  /**\n   * Requests an update for the content of the overlay.\n   * While performing the update, it invokes the renderer passed in the `renderer` property.\n   *\n   * It is not guaranteed that the update happens immediately (synchronously) after it is requested.\n   */\n  requestContentUpdate() {\n    if (this.renderer) {\n      this.renderer.call(this.owner, this, this.owner, this.model);\n    }\n  }\n\n  /** @private */\n  _mouseDownListener(event) {\n    this._mouseDownInside = event.composedPath().indexOf(this.$.overlay) >= 0;\n  }\n\n  /** @private */\n  _mouseUpListener(event) {\n    this._mouseUpInside = event.composedPath().indexOf(this.$.overlay) >= 0;\n  }\n\n  /**\n   * Whether to close the overlay on outside click or not.\n   * Override this method to customize the closing logic.\n   *\n   * @param {Event} _event\n   * @return {boolean}\n   * @protected\n   */\n  _shouldCloseOnOutsideClick(_event) {\n    return this._last;\n  }\n\n  /**\n   * Outside click listener used in capture phase to close the overlay before\n   * propagating the event to the listener on the element that triggered it.\n   * Otherwise, calling `open()` would result in closing and re-opening.\n   *\n   * @private\n   */\n  _outsideClickListener(event) {\n    if (event.composedPath().includes(this.$.overlay) || this._mouseDownInside || this._mouseUpInside) {\n      this._mouseDownInside = false;\n      this._mouseUpInside = false;\n      return;\n    }\n\n    if (!this._shouldCloseOnOutsideClick(event)) {\n      return;\n    }\n\n    const evt = new CustomEvent('vaadin-overlay-outside-click', {\n      bubbles: true,\n      cancelable: true,\n      detail: { sourceEvent: event },\n    });\n    this.dispatchEvent(evt);\n\n    if (this.opened && !evt.defaultPrevented) {\n      this.close(event);\n    }\n  }\n\n  /**\n   * Listener used to close whe overlay on Escape press, if it is the last one.\n   * @private\n   */\n  _keydownListener(event) {\n    if (!this._last) {\n      return;\n    }\n\n    // Only close modeless overlay on Esc press when it contains focus\n    if (this.modeless && !event.composedPath().includes(this.$.overlay)) {\n      return;\n    }\n\n    if (event.key === 'Escape') {\n      const evt = new CustomEvent('vaadin-overlay-escape-press', {\n        bubbles: true,\n        cancelable: true,\n        detail: { sourceEvent: event },\n      });\n      this.dispatchEvent(evt);\n\n      if (this.opened && !evt.defaultPrevented) {\n        this.close(event);\n      }\n    }\n  }\n\n  /** @private */\n  _openedChanged(opened, wasOpened) {\n    if (opened) {\n      this._saveFocus();\n\n      this._animatedOpening();\n\n      afterNextRender(this, () => {\n        this._trapFocus();\n\n        const evt = new CustomEvent('vaadin-overlay-open', { bubbles: true });\n        this.dispatchEvent(evt);\n      });\n\n      document.addEventListener('keydown', this._boundKeydownListener);\n\n      if (!this.modeless) {\n        this._addGlobalListeners();\n      }\n    } else if (wasOpened) {\n      this._resetFocus();\n\n      this._animatedClosing();\n\n      document.removeEventListener('keydown', this._boundKeydownListener);\n\n      if (!this.modeless) {\n        this._removeGlobalListeners();\n      }\n    }\n  }\n\n  /** @private */\n  _hiddenChanged(hidden) {\n    if (hidden && this.hasAttribute('closing')) {\n      this._flushAnimation('closing');\n    }\n  }\n\n  /**\n   * @return {boolean}\n   * @private\n   */\n  _shouldAnimate() {\n    const style = getComputedStyle(this);\n    const name = style.getPropertyValue('animation-name');\n    const hidden = style.getPropertyValue('display') === 'none';\n    return !hidden && name && name !== 'none';\n  }\n\n  /**\n   * @param {string} type\n   * @param {Function} callback\n   * @private\n   */\n  _enqueueAnimation(type, callback) {\n    const handler = `__${type}Handler`;\n    const listener = (event) => {\n      if (event && event.target !== this) {\n        return;\n      }\n      callback();\n      this.removeEventListener('animationend', listener);\n      delete this[handler];\n    };\n    this[handler] = listener;\n    this.addEventListener('animationend', listener);\n  }\n\n  /**\n   * @param {string} type\n   * @protected\n   */\n  _flushAnimation(type) {\n    const handler = `__${type}Handler`;\n    if (typeof this[handler] === 'function') {\n      this[handler]();\n    }\n  }\n\n  /** @private */\n  _animatedOpening() {\n    if (this.parentNode === document.body && this.hasAttribute('closing')) {\n      this._flushAnimation('closing');\n    }\n    this._attachOverlay();\n    if (!this.modeless) {\n      this._enterModalState();\n    }\n    this.setAttribute('opening', '');\n\n    if (this._shouldAnimate()) {\n      this._enqueueAnimation('opening', () => {\n        this._finishOpening();\n      });\n    } else {\n      this._finishOpening();\n    }\n  }\n\n  /** @private */\n  _attachOverlay() {\n    this._placeholder = document.createComment('vaadin-overlay-placeholder');\n    this.parentNode.insertBefore(this._placeholder, this);\n    document.body.appendChild(this);\n    this.bringToFront();\n  }\n\n  /** @private */\n  _finishOpening() {\n    this.removeAttribute('opening');\n  }\n\n  /** @private */\n  _finishClosing() {\n    this._detachOverlay();\n    this.$.overlay.style.removeProperty('pointer-events');\n    this.removeAttribute('closing');\n    this.dispatchEvent(new CustomEvent('vaadin-overlay-closed'));\n  }\n\n  /** @private */\n  _animatedClosing() {\n    if (this.hasAttribute('opening')) {\n      this._flushAnimation('opening');\n    }\n    if (this._placeholder) {\n      this._exitModalState();\n      this.setAttribute('closing', '');\n      this.dispatchEvent(new CustomEvent('vaadin-overlay-closing'));\n\n      if (this._shouldAnimate()) {\n        this._enqueueAnimation('closing', () => {\n          this._finishClosing();\n        });\n      } else {\n        this._finishClosing();\n      }\n    }\n  }\n\n  /** @private */\n  _detachOverlay() {\n    this._placeholder.parentNode.insertBefore(this, this._placeholder);\n    this._placeholder.parentNode.removeChild(this._placeholder);\n  }\n\n  /** @private */\n  _modelessChanged(modeless) {\n    if (!modeless) {\n      if (this.opened) {\n        this._addGlobalListeners();\n        this._enterModalState();\n      }\n    } else {\n      this._removeGlobalListeners();\n      this._exitModalState();\n    }\n  }\n\n  /** @private */\n  _addGlobalListeners() {\n    document.addEventListener('mousedown', this._boundMouseDownListener);\n    document.addEventListener('mouseup', this._boundMouseUpListener);\n    // Firefox leaks click to document on contextmenu even if prevented\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=990614\n    document.documentElement.addEventListener('click', this._boundOutsideClickListener, true);\n  }\n\n  /** @private */\n  _enterModalState() {\n    if (document.body.style.pointerEvents !== 'none') {\n      // Set body pointer-events to 'none' to disable mouse interactions with\n      // other document nodes.\n      this._previousDocumentPointerEvents = document.body.style.pointerEvents;\n      document.body.style.pointerEvents = 'none';\n    }\n\n    // Disable pointer events in other attached overlays\n    Overlay.__attachedInstances.forEach((el) => {\n      if (el !== this) {\n        el.shadowRoot.querySelector('[part=\"overlay\"]').style.pointerEvents = 'none';\n      }\n    });\n  }\n\n  /** @private */\n  _removeGlobalListeners() {\n    document.removeEventListener('mousedown', this._boundMouseDownListener);\n    document.removeEventListener('mouseup', this._boundMouseUpListener);\n    document.documentElement.removeEventListener('click', this._boundOutsideClickListener, true);\n  }\n\n  /** @private */\n  _exitModalState() {\n    if (this._previousDocumentPointerEvents !== undefined) {\n      // Restore body pointer-events\n      document.body.style.pointerEvents = this._previousDocumentPointerEvents;\n      delete this._previousDocumentPointerEvents;\n    }\n\n    // Restore pointer events in the previous overlay(s)\n    const instances = Overlay.__attachedInstances;\n    let el;\n    // Use instances.pop() to ensure the reverse order\n    while ((el = instances.pop())) {\n      if (el === this) {\n        // Skip the current instance\n        continue;\n      }\n      el.shadowRoot.querySelector('[part=\"overlay\"]').style.removeProperty('pointer-events');\n      if (!el.modeless) {\n        // Stop after the last modal\n        break;\n      }\n    }\n  }\n\n  /** @private */\n  _rendererOrDataChanged(renderer, owner, model, opened) {\n    const ownerOrModelChanged = this._oldOwner !== owner || this._oldModel !== model;\n    this._oldModel = model;\n    this._oldOwner = owner;\n\n    const rendererChanged = this._oldRenderer !== renderer;\n    this._oldRenderer = renderer;\n\n    const openedChanged = this._oldOpened !== opened;\n    this._oldOpened = opened;\n\n    if (rendererChanged) {\n      this.innerHTML = '';\n      // Whenever a Lit-based renderer is used, it assigns a Lit part to the node it was rendered into.\n      // When clearing the rendered content, this part needs to be manually disposed of.\n      // Otherwise, using a Lit-based renderer on the same node will throw an exception or render nothing afterward.\n      delete this._$litPart$;\n    }\n\n    if (opened && renderer && (rendererChanged || openedChanged || ownerOrModelChanged)) {\n      this.requestContentUpdate();\n    }\n  }\n\n  /**\n   * Brings the overlay as visually the frontmost one\n   */\n  bringToFront() {\n    let zIndex = '';\n    const frontmost = Overlay.__attachedInstances.filter((o) => o !== this).pop();\n    if (frontmost) {\n      const frontmostZIndex = frontmost.__zIndex;\n      zIndex = frontmostZIndex + 1;\n    }\n    this.style.zIndex = zIndex;\n    this.__zIndex = zIndex || parseFloat(getComputedStyle(this).zIndex);\n  }\n\n  /**\n   * @event vaadin-overlay-open\n   * Fired after the overlay is opened.\n   */\n\n  /**\n   * @event vaadin-overlay-close\n   * Fired when the opened overlay is about to be closed.\n   * Calling `preventDefault()` on the event cancels the closing.\n   */\n\n  /**\n   * @event vaadin-overlay-closing\n   * Fired when the overlay starts to close.\n   * Closing the overlay can be asynchronous depending on the animation.\n   */\n\n  /**\n   * @event vaadin-overlay-closed\n   * Fired after the overlay is closed.\n   */\n\n  /**\n   * @event vaadin-overlay-escape-press\n   * Fired before the overlay is closed on Escape key press.\n   * Calling `preventDefault()` on the event cancels the closing.\n   */\n\n  /**\n   * @event vaadin-overlay-outside-click\n   * Fired before the overlay is closed on outside click.\n   * Calling `preventDefault()` on the event cancels the closing.\n   */\n}\n\ncustomElements.define(Overlay.is, Overlay);\n\nexport { Overlay };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '../spacing.js';\nimport '../style.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { overlay } from './overlay.js';\n\nconst menuOverlayCore = css`\n  :host([opening]),\n  :host([closing]) {\n    animation: 0.14s lumo-overlay-dummy-animation;\n  }\n\n  [part='overlay'] {\n    will-change: opacity, transform;\n  }\n\n  :host([opening]) [part='overlay'] {\n    animation: 0.1s lumo-menu-overlay-enter ease-out both;\n  }\n\n  @keyframes lumo-menu-overlay-enter {\n    0% {\n      opacity: 0;\n      transform: translateY(-4px);\n    }\n  }\n\n  :host([closing]) [part='overlay'] {\n    animation: 0.1s lumo-menu-overlay-exit both;\n  }\n\n  @keyframes lumo-menu-overlay-exit {\n    100% {\n      opacity: 0;\n    }\n  }\n`;\n\nregisterStyles('', menuOverlayCore, { moduleId: 'lumo-menu-overlay-core' });\n\nconst menuOverlayExt = css`\n  /* Small viewport (bottom sheet) styles */\n  /* Use direct media queries instead of the state attributes ([phone] and [fullscreen]) provided by the elements */\n  @media (max-width: 420px), (max-height: 420px) {\n    :host {\n      top: 0 !important;\n      right: 0 !important;\n      bottom: var(--vaadin-overlay-viewport-bottom, 0) !important;\n      left: 0 !important;\n      align-items: stretch !important;\n      justify-content: flex-end !important;\n    }\n\n    [part='overlay'] {\n      max-height: 50vh;\n      width: 100vw;\n      border-radius: 0;\n      box-shadow: var(--lumo-box-shadow-xl);\n    }\n\n    /* The content part scrolls instead of the overlay part, because of the gradient fade-out */\n    [part='content'] {\n      padding: 30px var(--lumo-space-m);\n      max-height: inherit;\n      box-sizing: border-box;\n      -webkit-overflow-scrolling: touch;\n      overflow: auto;\n      -webkit-mask-image: linear-gradient(transparent, #000 40px, #000 calc(100% - 40px), transparent);\n      mask-image: linear-gradient(transparent, #000 40px, #000 calc(100% - 40px), transparent);\n    }\n\n    [part='backdrop'] {\n      display: block;\n    }\n\n    /* Animations */\n\n    :host([opening]) [part='overlay'] {\n      animation: 0.2s lumo-mobile-menu-overlay-enter cubic-bezier(0.215, 0.61, 0.355, 1) both;\n    }\n\n    :host([closing]),\n    :host([closing]) [part='backdrop'] {\n      animation-delay: 0.14s;\n    }\n\n    :host([closing]) [part='overlay'] {\n      animation: 0.14s 0.14s lumo-mobile-menu-overlay-exit cubic-bezier(0.55, 0.055, 0.675, 0.19) both;\n    }\n  }\n\n  @keyframes lumo-mobile-menu-overlay-enter {\n    0% {\n      transform: translateY(150%);\n    }\n  }\n\n  @keyframes lumo-mobile-menu-overlay-exit {\n    100% {\n      transform: translateY(150%);\n    }\n  }\n`;\n\nconst menuOverlay = [overlay, menuOverlayCore, menuOverlayExt];\n\nregisterStyles('', menuOverlay, { moduleId: 'lumo-menu-overlay' });\n\nexport { menuOverlayCore, menuOverlay };\n","import '@vaadin/vaadin-lumo-styles/sizing.js';\nimport '@vaadin/vaadin-lumo-styles/spacing.js';\nimport '@vaadin/overlay/theme/lumo/vaadin-overlay.js';\nimport { menuOverlay } from '@vaadin/vaadin-lumo-styles/mixins/menu-overlay.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst datePickerOverlay = css`\n  [part='overlay'] {\n    /*\n  Width:\n      date cell widths\n    + month calendar side padding\n    + year scroller width\n  */\n    /* prettier-ignore */\n    width:\n    calc(\n        var(--lumo-size-m) * 7\n      + var(--lumo-space-xs) * 2\n      + 57px\n    );\n    height: 100%;\n    max-height: calc(var(--lumo-size-m) * 14);\n    overflow: hidden;\n    -webkit-tap-highlight-color: transparent;\n  }\n\n  [part='overlay'] {\n    flex-direction: column;\n  }\n\n  [part='content'] {\n    padding: 0;\n    height: 100%;\n    overflow: hidden;\n    -webkit-mask-image: none;\n    mask-image: none;\n  }\n\n  :host([top-aligned]) [part~='overlay'] {\n    margin-top: var(--lumo-space-xs);\n  }\n\n  :host([bottom-aligned]) [part~='overlay'] {\n    margin-bottom: var(--lumo-space-xs);\n  }\n\n  @media (max-width: 420px), (max-height: 420px) {\n    [part='overlay'] {\n      width: 100vw;\n      height: 70vh;\n      max-height: 70vh;\n    }\n  }\n`;\n\nregisterStyles('vaadin-date-picker-overlay', [menuOverlay, datePickerOverlay], {\n  moduleId: 'lumo-date-picker-overlay',\n});\n","import '@vaadin/vaadin-lumo-styles/color.js';\nimport '@vaadin/vaadin-lumo-styles/sizing.js';\nimport '@vaadin/vaadin-lumo-styles/spacing.js';\nimport '@vaadin/vaadin-lumo-styles/style.js';\nimport '@vaadin/vaadin-lumo-styles/typography.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst button = css`\n  :host {\n    /* Sizing */\n    --lumo-button-size: var(--lumo-size-m);\n    min-width: calc(var(--lumo-button-size) * 2);\n    height: var(--lumo-button-size);\n    padding: 0 calc(var(--lumo-button-size) / 3 + var(--lumo-border-radius-m) / 2);\n    margin: var(--lumo-space-xs) 0;\n    box-sizing: border-box;\n    /* Style */\n    font-family: var(--lumo-font-family);\n    font-size: var(--lumo-font-size-m);\n    font-weight: 500;\n    color: var(--_lumo-button-color, var(--lumo-primary-text-color));\n    background-color: var(--_lumo-button-background-color, var(--lumo-contrast-5pct));\n    border-radius: var(--lumo-border-radius-m);\n    cursor: var(--lumo-clickable-cursor);\n    -webkit-tap-highlight-color: transparent;\n    -webkit-font-smoothing: antialiased;\n    -moz-osx-font-smoothing: grayscale;\n    flex-shrink: 0;\n  }\n\n  /* Set only for the internal parts so we don't affect the host vertical alignment */\n  [part='label'],\n  [part='prefix'],\n  [part='suffix'] {\n    line-height: var(--lumo-line-height-xs);\n  }\n\n  [part='label'] {\n    padding: calc(var(--lumo-button-size) / 6) 0;\n  }\n\n  :host([theme~='small']) {\n    font-size: var(--lumo-font-size-s);\n    --lumo-button-size: var(--lumo-size-s);\n  }\n\n  :host([theme~='large']) {\n    font-size: var(--lumo-font-size-l);\n    --lumo-button-size: var(--lumo-size-l);\n  }\n\n  /* For interaction states */\n  :host::before,\n  :host::after {\n    content: '';\n    /* We rely on the host always being relative */\n    position: absolute;\n    z-index: 1;\n    top: 0;\n    right: 0;\n    bottom: 0;\n    left: 0;\n    background-color: currentColor;\n    border-radius: inherit;\n    opacity: 0;\n    pointer-events: none;\n  }\n\n  /* Hover */\n\n  @media (any-hover: hover) {\n    :host(:hover)::before {\n      opacity: 0.02;\n    }\n  }\n\n  /* Active */\n\n  :host::after {\n    transition: opacity 1.4s, transform 0.1s;\n    filter: blur(8px);\n  }\n\n  :host([active])::before {\n    opacity: 0.05;\n    transition-duration: 0s;\n  }\n\n  :host([active])::after {\n    opacity: 0.1;\n    transition-duration: 0s, 0s;\n    transform: scale(0);\n  }\n\n  /* Keyboard focus */\n\n  :host([focus-ring]) {\n    box-shadow: 0 0 0 2px var(--lumo-primary-color-50pct);\n  }\n\n  :host([theme~='primary'][focus-ring]) {\n    box-shadow: 0 0 0 1px var(--lumo-base-color), 0 0 0 3px var(--lumo-primary-color-50pct);\n  }\n\n  /* Types (primary, tertiary, tertiary-inline */\n\n  :host([theme~='tertiary']),\n  :host([theme~='tertiary-inline']) {\n    background-color: transparent !important;\n    min-width: 0;\n  }\n\n  :host([theme~='tertiary']) {\n    padding: 0 calc(var(--lumo-button-size) / 6);\n  }\n\n  :host([theme~='tertiary-inline'])::before {\n    display: none;\n  }\n\n  :host([theme~='tertiary-inline']) {\n    margin: 0;\n    height: auto;\n    padding: 0;\n    line-height: inherit;\n    font-size: inherit;\n  }\n\n  :host([theme~='tertiary-inline']) [part='label'] {\n    padding: 0;\n    overflow: visible;\n    line-height: inherit;\n  }\n\n  :host([theme~='primary']) {\n    background-color: var(--_lumo-button-primary-background-color, var(--lumo-primary-color));\n    color: var(--_lumo-button-primary-color, var(--lumo-primary-contrast-color));\n    font-weight: 600;\n    min-width: calc(var(--lumo-button-size) * 2.5);\n  }\n\n  :host([theme~='primary'])::before {\n    background-color: black;\n  }\n\n  @media (any-hover: hover) {\n    :host([theme~='primary']:hover)::before {\n      opacity: 0.05;\n    }\n  }\n\n  :host([theme~='primary'][active])::before {\n    opacity: 0.1;\n  }\n\n  :host([theme~='primary'][active])::after {\n    opacity: 0.2;\n  }\n\n  /* Colors (success, error, contrast) */\n\n  :host([theme~='success']) {\n    color: var(--lumo-success-text-color);\n  }\n\n  :host([theme~='success'][theme~='primary']) {\n    background-color: var(--lumo-success-color);\n    color: var(--lumo-success-contrast-color);\n  }\n\n  :host([theme~='error']) {\n    color: var(--lumo-error-text-color);\n  }\n\n  :host([theme~='error'][theme~='primary']) {\n    background-color: var(--lumo-error-color);\n    color: var(--lumo-error-contrast-color);\n  }\n\n  :host([theme~='contrast']) {\n    color: var(--lumo-contrast);\n  }\n\n  :host([theme~='contrast'][theme~='primary']) {\n    background-color: var(--lumo-contrast);\n    color: var(--lumo-base-color);\n  }\n\n  /* Disabled state. Keep selectors after other color variants. */\n\n  :host([disabled]) {\n    pointer-events: none;\n    color: var(--lumo-disabled-text-color);\n  }\n\n  :host([theme~='primary'][disabled]) {\n    background-color: var(--lumo-contrast-30pct);\n    color: var(--lumo-base-color);\n  }\n\n  :host([theme~='primary'][disabled]) [part] {\n    opacity: 0.7;\n  }\n\n  /* Icons */\n\n  [part] ::slotted(vaadin-icon) {\n    display: inline-block;\n    width: var(--lumo-icon-size-m);\n    height: var(--lumo-icon-size-m);\n  }\n\n  /* Vaadin icons are based on a 16x16 grid (unlike Lumo and Material icons with 24x24), so they look too big by default */\n  [part] ::slotted(vaadin-icon[icon^='vaadin:']) {\n    padding: 0.25em;\n    box-sizing: border-box !important;\n  }\n\n  [part='prefix'] {\n    margin-left: -0.25em;\n    margin-right: 0.25em;\n  }\n\n  [part='suffix'] {\n    margin-left: 0.25em;\n    margin-right: -0.25em;\n  }\n\n  /* Icon-only */\n\n  :host([theme~='icon']:not([theme~='tertiary-inline'])) {\n    min-width: var(--lumo-button-size);\n    padding-left: calc(var(--lumo-button-size) / 4);\n    padding-right: calc(var(--lumo-button-size) / 4);\n  }\n\n  :host([theme~='icon']) [part='prefix'],\n  :host([theme~='icon']) [part='suffix'] {\n    margin-left: 0;\n    margin-right: 0;\n  }\n\n  /* RTL specific styles */\n\n  :host([dir='rtl']) [part='prefix'] {\n    margin-left: 0.25em;\n    margin-right: -0.25em;\n  }\n\n  :host([dir='rtl']) [part='suffix'] {\n    margin-left: -0.25em;\n    margin-right: 0.25em;\n  }\n\n  :host([dir='rtl'][theme~='icon']) [part='prefix'],\n  :host([dir='rtl'][theme~='icon']) [part='suffix'] {\n    margin-left: 0;\n    margin-right: 0;\n  }\n`;\n\nregisterStyles('vaadin-button', button, { moduleId: 'lumo-button' });\n\nexport { button };\n","const DEV_MODE_CODE_REGEXP =\n  /\\/\\*[\\*!]\\s+vaadin-dev-mode:start([\\s\\S]*)vaadin-dev-mode:end\\s+\\*\\*\\//i;\n\nconst FlowClients = window.Vaadin && window.Vaadin.Flow && window.Vaadin.Flow.clients;\n\nfunction isMinified() {\n  function test() {\n    /** vaadin-dev-mode:start\n    return false;\n    vaadin-dev-mode:end **/\n    return true;\n  }\n  return uncommentAndRun(test);\n}\n\nfunction isDevelopmentMode() {\n  try {\n    if (isForcedDevelopmentMode()) {\n      return true;\n    }\n\n    if (!isLocalhost()) {\n      return false;\n    }\n\n    if (FlowClients) {\n      return !isFlowProductionMode();\n    }\n\n    return !isMinified();\n  } catch (e) {\n    // Some error in this code, assume production so no further actions will be taken\n    return false;\n  }\n}\n\nfunction isForcedDevelopmentMode() {\n  return localStorage.getItem(\"vaadin.developmentmode.force\");\n}\n\nfunction isLocalhost() {\n  return ([\"localhost\",\"127.0.0.1\"].indexOf(window.location.hostname) >= 0);\n}\n\nfunction isFlowProductionMode() {\n  if (FlowClients) {\n    const productionModeApps = Object.keys(FlowClients)\n      .map(key => FlowClients[key])\n      .filter(client => client.productionMode);\n    if (productionModeApps.length > 0) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction uncommentAndRun(callback, args) {\n  if (typeof callback !== 'function') {\n    return;\n  }\n\n  const match = DEV_MODE_CODE_REGEXP.exec(callback.toString());\n  if (match) {\n    try {\n      // requires CSP: script-src 'unsafe-eval'\n      callback = new Function(match[1]);\n    } catch (e) {\n      // eat the exception\n      console.log('vaadin-development-mode-detector: uncommentAndRun() failed', e)\n    }\n  }\n\n  return callback(args);\n}\n\n// A guard against polymer-modulizer removing the window.Vaadin\n// initialization above.\nwindow['Vaadin'] = window['Vaadin'] || {};\n\n/**\n * Inspects the source code of the given `callback` function for\n * specially-marked _commented_ code. If such commented code is found in the\n * callback source, uncomments and runs that code instead of the callback\n * itself. Otherwise runs the callback as is.\n *\n * The optional arguments are passed into the callback / uncommented code,\n * the result is returned.\n *\n * See the `isMinified()` function source code in this file for an example.\n *\n */\nexport const runIfDevelopmentMode = function(callback, args) {\n  if (window.Vaadin.developmentMode) {\n    return uncommentAndRun(callback, args);\n  }\n};\n\nif (window.Vaadin.developmentMode === undefined) {\n  window.Vaadin.developmentMode = isDevelopmentMode();\n}\n","/* This file is autogenerated from src/vaadin-usage-statistics.tpl.html */\n/*\n\nThis script gathers usage statistics from the application running in development mode.\n\nStatistics gathering is automatically disabled and excluded from production builds.\n\nFor details and to opt-out, see https://github.com/vaadin/vaadin-usage-statistics.\n\n*/\n/*\n  FIXME(polymer-modulizer): the above comments were extracted\n  from HTML and may be out of place here. Review them and\n  then delete this comment!\n*/\nimport { runIfDevelopmentMode } from '@vaadin/vaadin-development-mode-detector/vaadin-development-mode-detector.js';\n\nfunction maybeGatherAndSendStats() {\n  /** vaadin-dev-mode:start\n  (function () {\n'use strict';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n  return typeof obj;\n} : function (obj) {\n  return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n};\n\nvar classCallCheck = function (instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n};\n\nvar createClass = function () {\n  function defineProperties(target, props) {\n    for (var i = 0; i < props.length; i++) {\n      var descriptor = props[i];\n      descriptor.enumerable = descriptor.enumerable || false;\n      descriptor.configurable = true;\n      if (\"value\" in descriptor) descriptor.writable = true;\n      Object.defineProperty(target, descriptor.key, descriptor);\n    }\n  }\n\n  return function (Constructor, protoProps, staticProps) {\n    if (protoProps) defineProperties(Constructor.prototype, protoProps);\n    if (staticProps) defineProperties(Constructor, staticProps);\n    return Constructor;\n  };\n}();\n\nvar getPolymerVersion = function getPolymerVersion() {\n  return window.Polymer && window.Polymer.version;\n};\n\nvar StatisticsGatherer = function () {\n  function StatisticsGatherer(logger) {\n    classCallCheck(this, StatisticsGatherer);\n\n    this.now = new Date().getTime();\n    this.logger = logger;\n  }\n\n  createClass(StatisticsGatherer, [{\n    key: 'frameworkVersionDetectors',\n    value: function frameworkVersionDetectors() {\n      return {\n        'Flow': function Flow() {\n          if (window.Vaadin && window.Vaadin.Flow && window.Vaadin.Flow.clients) {\n            var flowVersions = Object.keys(window.Vaadin.Flow.clients).map(function (key) {\n              return window.Vaadin.Flow.clients[key];\n            }).filter(function (client) {\n              return client.getVersionInfo;\n            }).map(function (client) {\n              return client.getVersionInfo().flow;\n            });\n            if (flowVersions.length > 0) {\n              return flowVersions[0];\n            }\n          }\n        },\n        'Vaadin Framework': function VaadinFramework() {\n          if (window.vaadin && window.vaadin.clients) {\n            var frameworkVersions = Object.values(window.vaadin.clients).filter(function (client) {\n              return client.getVersionInfo;\n            }).map(function (client) {\n              return client.getVersionInfo().vaadinVersion;\n            });\n            if (frameworkVersions.length > 0) {\n              return frameworkVersions[0];\n            }\n          }\n        },\n        'AngularJs': function AngularJs() {\n          if (window.angular && window.angular.version && window.angular.version) {\n            return window.angular.version.full;\n          }\n        },\n        'Angular': function Angular() {\n          if (window.ng) {\n            var tags = document.querySelectorAll(\"[ng-version]\");\n            if (tags.length > 0) {\n              return tags[0].getAttribute(\"ng-version\");\n            }\n            return \"Unknown\";\n          }\n        },\n        'Backbone.js': function BackboneJs() {\n          if (window.Backbone) {\n            return window.Backbone.VERSION;\n          }\n        },\n        'React': function React() {\n          var reactSelector = '[data-reactroot], [data-reactid]';\n          if (!!document.querySelector(reactSelector)) {\n            // React does not publish the version by default\n            return \"unknown\";\n          }\n        },\n        'Ember': function Ember() {\n          if (window.Em && window.Em.VERSION) {\n            return window.Em.VERSION;\n          } else if (window.Ember && window.Ember.VERSION) {\n            return window.Ember.VERSION;\n          }\n        },\n        'jQuery': function (_jQuery) {\n          function jQuery() {\n            return _jQuery.apply(this, arguments);\n          }\n\n          jQuery.toString = function () {\n            return _jQuery.toString();\n          };\n\n          return jQuery;\n        }(function () {\n          if (typeof jQuery === 'function' && jQuery.prototype.jquery !== undefined) {\n            return jQuery.prototype.jquery;\n          }\n        }),\n        'Polymer': function Polymer() {\n          var version = getPolymerVersion();\n          if (version) {\n            return version;\n          }\n        },\n        'LitElement': function LitElement() {\n          var version = window.litElementVersions && window.litElementVersions[0];\n          if (version) {\n            return version;\n          }\n        },\n        'LitHtml': function LitHtml() {\n          var version = window.litHtmlVersions && window.litHtmlVersions[0];\n          if (version) {\n            return version;\n          }\n        },\n        'Vue.js': function VueJs() {\n          if (window.Vue) {\n            return window.Vue.version;\n          }\n        }\n      };\n    }\n  }, {\n    key: 'getUsedVaadinElements',\n    value: function getUsedVaadinElements(elements) {\n      var version = getPolymerVersion();\n      var elementClasses = void 0;\n      // NOTE: In case you edit the code here, YOU MUST UPDATE any statistics reporting code in Flow.\n      // Check all locations calling the method getEntries() in\n      // https://github.com/vaadin/flow/blob/master/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatistics.java#L106\n      // Currently it is only used by BootstrapHandler.\n      if (version && version.indexOf('2') === 0) {\n        // Polymer 2: components classes are stored in window.Vaadin\n        elementClasses = Object.keys(window.Vaadin).map(function (c) {\n          return window.Vaadin[c];\n        }).filter(function (c) {\n          return c.is;\n        });\n      } else {\n        // Polymer 3: components classes are stored in window.Vaadin.registrations\n        elementClasses = window.Vaadin.registrations || [];\n      }\n      elementClasses.forEach(function (klass) {\n        var version = klass.version ? klass.version : \"0.0.0\";\n        elements[klass.is] = { version: version };\n      });\n    }\n  }, {\n    key: 'getUsedVaadinThemes',\n    value: function getUsedVaadinThemes(themes) {\n      ['Lumo', 'Material'].forEach(function (themeName) {\n        var theme;\n        var version = getPolymerVersion();\n        if (version && version.indexOf('2') === 0) {\n          // Polymer 2: themes are stored in window.Vaadin\n          theme = window.Vaadin[themeName];\n        } else {\n          // Polymer 3: themes are stored in custom element registry\n          theme = customElements.get('vaadin-' + themeName.toLowerCase() + '-styles');\n        }\n        if (theme && theme.version) {\n          themes[themeName] = { version: theme.version };\n        }\n      });\n    }\n  }, {\n    key: 'getFrameworks',\n    value: function getFrameworks(frameworks) {\n      var detectors = this.frameworkVersionDetectors();\n      Object.keys(detectors).forEach(function (framework) {\n        var detector = detectors[framework];\n        try {\n          var version = detector();\n          if (version) {\n            frameworks[framework] = { version: version };\n          }\n        } catch (e) {}\n      });\n    }\n  }, {\n    key: 'gather',\n    value: function gather(storage) {\n      var storedStats = storage.read();\n      var gatheredStats = {};\n      var types = [\"elements\", \"frameworks\", \"themes\"];\n\n      types.forEach(function (type) {\n        gatheredStats[type] = {};\n        if (!storedStats[type]) {\n          storedStats[type] = {};\n        }\n      });\n\n      var previousStats = JSON.stringify(storedStats);\n\n      this.getUsedVaadinElements(gatheredStats.elements);\n      this.getFrameworks(gatheredStats.frameworks);\n      this.getUsedVaadinThemes(gatheredStats.themes);\n\n      var now = this.now;\n      types.forEach(function (type) {\n        var keys = Object.keys(gatheredStats[type]);\n        keys.forEach(function (key) {\n          if (!storedStats[type][key] || _typeof(storedStats[type][key]) != _typeof({})) {\n            storedStats[type][key] = { firstUsed: now };\n          }\n          // Discards any previously logged version number\n          storedStats[type][key].version = gatheredStats[type][key].version;\n          storedStats[type][key].lastUsed = now;\n        });\n      });\n\n      var newStats = JSON.stringify(storedStats);\n      storage.write(newStats);\n      if (newStats != previousStats && Object.keys(storedStats).length > 0) {\n        this.logger.debug(\"New stats: \" + newStats);\n      }\n    }\n  }]);\n  return StatisticsGatherer;\n}();\n\nvar StatisticsStorage = function () {\n  function StatisticsStorage(key) {\n    classCallCheck(this, StatisticsStorage);\n\n    this.key = key;\n  }\n\n  createClass(StatisticsStorage, [{\n    key: 'read',\n    value: function read() {\n      var localStorageStatsString = localStorage.getItem(this.key);\n      try {\n        return JSON.parse(localStorageStatsString ? localStorageStatsString : '{}');\n      } catch (e) {\n        return {};\n      }\n    }\n  }, {\n    key: 'write',\n    value: function write(data) {\n      localStorage.setItem(this.key, data);\n    }\n  }, {\n    key: 'clear',\n    value: function clear() {\n      localStorage.removeItem(this.key);\n    }\n  }, {\n    key: 'isEmpty',\n    value: function isEmpty() {\n      var storedStats = this.read();\n      var empty = true;\n      Object.keys(storedStats).forEach(function (key) {\n        if (Object.keys(storedStats[key]).length > 0) {\n          empty = false;\n        }\n      });\n\n      return empty;\n    }\n  }]);\n  return StatisticsStorage;\n}();\n\nvar StatisticsSender = function () {\n  function StatisticsSender(url, logger) {\n    classCallCheck(this, StatisticsSender);\n\n    this.url = url;\n    this.logger = logger;\n  }\n\n  createClass(StatisticsSender, [{\n    key: 'send',\n    value: function send(data, errorHandler) {\n      var logger = this.logger;\n\n      if (navigator.onLine === false) {\n        logger.debug(\"Offline, can't send\");\n        errorHandler();\n        return;\n      }\n      logger.debug(\"Sending data to \" + this.url);\n\n      var req = new XMLHttpRequest();\n      req.withCredentials = true;\n      req.addEventListener(\"load\", function () {\n        // Stats sent, nothing more to do\n        logger.debug(\"Response: \" + req.responseText);\n      });\n      req.addEventListener(\"error\", function () {\n        logger.debug(\"Send failed\");\n        errorHandler();\n      });\n      req.addEventListener(\"abort\", function () {\n        logger.debug(\"Send aborted\");\n        errorHandler();\n      });\n      req.open(\"POST\", this.url);\n      req.setRequestHeader(\"Content-Type\", \"application/json\");\n      req.send(data);\n    }\n  }]);\n  return StatisticsSender;\n}();\n\nvar StatisticsLogger = function () {\n  function StatisticsLogger(id) {\n    classCallCheck(this, StatisticsLogger);\n\n    this.id = id;\n  }\n\n  createClass(StatisticsLogger, [{\n    key: '_isDebug',\n    value: function _isDebug() {\n      return localStorage.getItem(\"vaadin.\" + this.id + \".debug\");\n    }\n  }, {\n    key: 'debug',\n    value: function debug(msg) {\n      if (this._isDebug()) {\n        console.info(this.id + \": \" + msg);\n      }\n    }\n  }]);\n  return StatisticsLogger;\n}();\n\nvar UsageStatistics = function () {\n  function UsageStatistics() {\n    classCallCheck(this, UsageStatistics);\n\n    this.now = new Date();\n    this.timeNow = this.now.getTime();\n    this.gatherDelay = 10; // Delay between loading this file and gathering stats\n    this.initialDelay = 24 * 60 * 60;\n\n    this.logger = new StatisticsLogger(\"statistics\");\n    this.storage = new StatisticsStorage(\"vaadin.statistics.basket\");\n    this.gatherer = new StatisticsGatherer(this.logger);\n    this.sender = new StatisticsSender(\"https://tools.vaadin.com/usage-stats/submit\", this.logger);\n  }\n\n  createClass(UsageStatistics, [{\n    key: 'maybeGatherAndSend',\n    value: function maybeGatherAndSend() {\n      var _this = this;\n\n      if (localStorage.getItem(UsageStatistics.optOutKey)) {\n        return;\n      }\n      this.gatherer.gather(this.storage);\n      setTimeout(function () {\n        _this.maybeSend();\n      }, this.gatherDelay * 1000);\n    }\n  }, {\n    key: 'lottery',\n    value: function lottery() {\n      return true;\n    }\n  }, {\n    key: 'currentMonth',\n    value: function currentMonth() {\n      return this.now.getYear() * 12 + this.now.getMonth();\n    }\n  }, {\n    key: 'maybeSend',\n    value: function maybeSend() {\n      var firstUse = Number(localStorage.getItem(UsageStatistics.firstUseKey));\n      var monthProcessed = Number(localStorage.getItem(UsageStatistics.monthProcessedKey));\n\n      if (!firstUse) {\n        // Use a grace period to avoid interfering with tests, incognito mode etc\n        firstUse = this.timeNow;\n        localStorage.setItem(UsageStatistics.firstUseKey, firstUse);\n      }\n\n      if (this.timeNow < firstUse + this.initialDelay * 1000) {\n        this.logger.debug(\"No statistics will be sent until the initial delay of \" + this.initialDelay + \"s has passed\");\n        return;\n      }\n      if (this.currentMonth() <= monthProcessed) {\n        this.logger.debug(\"This month has already been processed\");\n        return;\n      }\n      localStorage.setItem(UsageStatistics.monthProcessedKey, this.currentMonth());\n      // Use random sampling\n      if (this.lottery()) {\n        this.logger.debug(\"Congratulations, we have a winner!\");\n      } else {\n        this.logger.debug(\"Sorry, no stats from you this time\");\n        return;\n      }\n\n      this.send();\n    }\n  }, {\n    key: 'send',\n    value: function send() {\n      // Ensure we have the latest data\n      this.gatherer.gather(this.storage);\n\n      // Read, send and clean up\n      var data = this.storage.read();\n      data[\"firstUse\"] = Number(localStorage.getItem(UsageStatistics.firstUseKey));\n      data[\"usageStatisticsVersion\"] = UsageStatistics.version;\n      var info = 'This request contains usage statistics gathered from the application running in development mode. \\n\\nStatistics gathering is automatically disabled and excluded from production builds.\\n\\nFor details and to opt-out, see https://github.com/vaadin/vaadin-usage-statistics.\\n\\n\\n\\n';\n      var self = this;\n      this.sender.send(info + JSON.stringify(data), function () {\n        // Revert the 'month processed' flag\n        localStorage.setItem(UsageStatistics.monthProcessedKey, self.currentMonth() - 1);\n      });\n    }\n  }], [{\n    key: 'version',\n    get: function get$1() {\n      return '2.1.2';\n    }\n  }, {\n    key: 'firstUseKey',\n    get: function get$1() {\n      return 'vaadin.statistics.firstuse';\n    }\n  }, {\n    key: 'monthProcessedKey',\n    get: function get$1() {\n      return 'vaadin.statistics.monthProcessed';\n    }\n  }, {\n    key: 'optOutKey',\n    get: function get$1() {\n      return 'vaadin.statistics.optout';\n    }\n  }]);\n  return UsageStatistics;\n}();\n\ntry {\n  window.Vaadin = window.Vaadin || {};\n  window.Vaadin.usageStatsChecker = window.Vaadin.usageStatsChecker || new UsageStatistics();\n  window.Vaadin.usageStatsChecker.maybeGatherAndSend();\n} catch (e) {\n  // Intentionally ignored as this is not a problem in the app being developed\n}\n\n}());\n\n  vaadin-dev-mode:end **/\n}\n\nexport const usageStatistics = function() {\n  if (typeof runIfDevelopmentMode === 'function') {\n    return runIfDevelopmentMode(maybeGatherAndSendStats);\n  }\n};\n","/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n */\n\n/**\n * @fileoverview\n *\n * This module provides a number of strategies for enqueuing asynchronous\n * tasks. Each sub-module provides a standard `run(fn)` interface that returns a\n * handle, and a `cancel(handle)` interface for canceling async tasks before\n * they run.\n *\n * @summary Module that provides a number of strategies for enqueuing\n * asynchronous tasks.\n */\n\nlet microtaskCurrHandle = 0;\nlet microtaskLastHandle = 0;\nconst microtaskCallbacks = [];\nlet microtaskScheduled = false;\n\nfunction microtaskFlush() {\n  microtaskScheduled = false;\n  const len = microtaskCallbacks.length;\n  for (let i = 0; i < len; i++) {\n    const cb = microtaskCallbacks[i];\n    if (cb) {\n      try {\n        cb();\n      } catch (e) {\n        setTimeout(() => {\n          throw e;\n        });\n      }\n    }\n  }\n  microtaskCallbacks.splice(0, len);\n  microtaskLastHandle += len;\n}\n\n/**\n * Async interface wrapper around `setTimeout`.\n *\n * @namespace\n * @summary Async interface wrapper around `setTimeout`.\n */\nconst timeOut = {\n  /**\n   * Returns a sub-module with the async interface providing the provided\n   * delay.\n   *\n   * @memberof timeOut\n   * @param {number=} delay Time to wait before calling callbacks in ms\n   * @return {!AsyncInterface} An async timeout interface\n   */\n  after(delay) {\n    return {\n      run(fn) {\n        return window.setTimeout(fn, delay);\n      },\n      cancel(handle) {\n        window.clearTimeout(handle);\n      },\n    };\n  },\n  /**\n   * Enqueues a function called in the next task.\n   *\n   * @memberof timeOut\n   * @param {!Function} fn Callback to run\n   * @param {number=} delay Delay in milliseconds\n   * @return {number} Handle used for canceling task\n   */\n  run(fn, delay) {\n    return window.setTimeout(fn, delay);\n  },\n  /**\n   * Cancels a previously enqueued `timeOut` callback.\n   *\n   * @memberof timeOut\n   * @param {number} handle Handle returned from `run` of callback to cancel\n   * @return {void}\n   */\n  cancel(handle) {\n    window.clearTimeout(handle);\n  },\n};\nexport { timeOut };\n\n/**\n * Async interface wrapper around `requestAnimationFrame`.\n *\n * @namespace\n * @summary Async interface wrapper around `requestAnimationFrame`.\n */\nconst animationFrame = {\n  /**\n   * Enqueues a function called at `requestAnimationFrame` timing.\n   *\n   * @memberof animationFrame\n   * @param {function(number):void} fn Callback to run\n   * @return {number} Handle used for canceling task\n   */\n  run(fn) {\n    return window.requestAnimationFrame(fn);\n  },\n  /**\n   * Cancels a previously enqueued `animationFrame` callback.\n   *\n   * @memberof animationFrame\n   * @param {number} handle Handle returned from `run` of callback to cancel\n   * @return {void}\n   */\n  cancel(handle) {\n    window.cancelAnimationFrame(handle);\n  },\n};\nexport { animationFrame };\n\n/**\n * Async interface wrapper around `requestIdleCallback`.  Falls back to\n * `setTimeout` on browsers that do not support `requestIdleCallback`.\n *\n * @namespace\n * @summary Async interface wrapper around `requestIdleCallback`.\n */\nconst idlePeriod = {\n  /**\n   * Enqueues a function called at `requestIdleCallback` timing.\n   *\n   * @memberof idlePeriod\n   * @param {function(!IdleDeadline):void} fn Callback to run\n   * @return {number} Handle used for canceling task\n   */\n  run(fn) {\n    return window.requestIdleCallback ? window.requestIdleCallback(fn) : window.setTimeout(fn, 16);\n  },\n  /**\n   * Cancels a previously enqueued `idlePeriod` callback.\n   *\n   * @memberof idlePeriod\n   * @param {number} handle Handle returned from `run` of callback to cancel\n   * @return {void}\n   */\n  cancel(handle) {\n    if (window.cancelIdleCallback) {\n      window.cancelIdleCallback(handle);\n    } else {\n      window.clearTimeout(handle);\n    }\n  },\n};\nexport { idlePeriod };\n\n/**\n * Async interface for enqueuing callbacks that run at microtask timing.\n *\n * @namespace\n * @summary Async interface for enqueuing callbacks that run at microtask\n *   timing.\n */\nconst microTask = {\n  /**\n   * Enqueues a function called at microtask timing.\n   *\n   * @memberof microTask\n   * @param {!Function=} callback Callback to run\n   * @return {number} Handle used for canceling task\n   */\n  run(callback) {\n    if (!microtaskScheduled) {\n      microtaskScheduled = true;\n      queueMicrotask(() => microtaskFlush());\n    }\n    microtaskCallbacks.push(callback);\n    const result = microtaskCurrHandle;\n    microtaskCurrHandle += 1;\n    return result;\n  },\n\n  /**\n   * Cancels a previously enqueued `microTask` callback.\n   *\n   * @memberof microTask\n   * @param {number} handle Handle returned from `run` of callback to cancel\n   * @return {void}\n   */\n  cancel(handle) {\n    const idx = handle - microtaskLastHandle;\n    if (idx >= 0) {\n      if (!microtaskCallbacks[idx]) {\n        throw new Error(`invalid async handle: ${handle}`);\n      }\n      microtaskCallbacks[idx] = null;\n    }\n  },\n};\nexport { microTask };\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\nconst debouncerQueue = new Set();\n\n/**\n * @summary Collapse multiple callbacks into one invocation after a timer.\n */\nexport class Debouncer {\n  /**\n   * Creates a debouncer if no debouncer is passed as a parameter\n   * or it cancels an active debouncer otherwise. The following\n   * example shows how a debouncer can be called multiple times within a\n   * microtask and \"debounced\" such that the provided callback function is\n   * called once. Add this method to a custom element:\n   *\n   * ```js\n   * import {microTask} from '@vaadin/component-base/src/async.js';\n   * import {Debouncer} from '@vaadin/component-base/src/debounce.js';\n   * // ...\n   *\n   * _debounceWork() {\n   *   this._debounceJob = Debouncer.debounce(this._debounceJob,\n   *       microTask, () => this._doWork());\n   * }\n   * ```\n   *\n   * If the `_debounceWork` method is called multiple times within the same\n   * microtask, the `_doWork` function will be called only once at the next\n   * microtask checkpoint.\n   *\n   * Note: In testing it is often convenient to avoid asynchrony. To accomplish\n   * this with a debouncer, you can use `enqueueDebouncer` and\n   * `flush`. For example, extend the above example by adding\n   * `enqueueDebouncer(this._debounceJob)` at the end of the\n   * `_debounceWork` method. Then in a test, call `flush` to ensure\n   * the debouncer has completed.\n   *\n   * @param {Debouncer?} debouncer Debouncer object.\n   * @param {!AsyncInterface} asyncModule Object with Async interface\n   * @param {function()} callback Callback to run.\n   * @return {!Debouncer} Returns a debouncer object.\n   */\n  static debounce(debouncer, asyncModule, callback) {\n    if (debouncer instanceof Debouncer) {\n      // Cancel the async callback, but leave in debouncerQueue if it was\n      // enqueued, to maintain 1.x flush order\n      debouncer._cancelAsync();\n    } else {\n      debouncer = new Debouncer();\n    }\n    debouncer.setConfig(asyncModule, callback);\n    return debouncer;\n  }\n\n  constructor() {\n    this._asyncModule = null;\n    this._callback = null;\n    this._timer = null;\n  }\n\n  /**\n   * Sets the scheduler; that is, a module with the Async interface,\n   * a callback and optional arguments to be passed to the run function\n   * from the async module.\n   *\n   * @param {!AsyncInterface} asyncModule Object with Async interface.\n   * @param {function()} callback Callback to run.\n   * @return {void}\n   */\n  setConfig(asyncModule, callback) {\n    this._asyncModule = asyncModule;\n    this._callback = callback;\n    this._timer = this._asyncModule.run(() => {\n      this._timer = null;\n      debouncerQueue.delete(this);\n      this._callback();\n    });\n  }\n\n  /**\n   * Cancels an active debouncer and returns a reference to itself.\n   *\n   * @return {void}\n   */\n  cancel() {\n    if (this.isActive()) {\n      this._cancelAsync();\n      // Canceling a debouncer removes its spot from the flush queue,\n      // so if a debouncer is manually canceled and re-debounced, it\n      // will reset its flush order (this is a very minor difference from 1.x)\n      // Re-debouncing via the `debounce` API retains the 1.x FIFO flush order\n      debouncerQueue.delete(this);\n    }\n  }\n\n  /**\n   * Cancels a debouncer's async callback.\n   *\n   * @return {void}\n   */\n  _cancelAsync() {\n    if (this.isActive()) {\n      this._asyncModule.cancel(/** @type {number} */ (this._timer));\n      this._timer = null;\n    }\n  }\n\n  /**\n   * Flushes an active debouncer and returns a reference to itself.\n   *\n   * @return {void}\n   */\n  flush() {\n    if (this.isActive()) {\n      this.cancel();\n      this._callback();\n    }\n  }\n\n  /**\n   * Returns true if the debouncer is active.\n   *\n   * @return {boolean} True if active.\n   */\n  isActive() {\n    return this._timer != null;\n  }\n}\n\n/**\n * Adds a `Debouncer` to a list of globally flushable tasks.\n *\n * @param {!Debouncer} debouncer Debouncer to enqueue\n * @return {void}\n */\nexport function enqueueDebouncer(debouncer) {\n  debouncerQueue.add(debouncer);\n}\n\n/**\n * Flushes any enqueued debouncers\n *\n * @return {boolean} Returns whether any debouncers were flushed\n */\nexport function flushDebouncers() {\n  const didFlush = Boolean(debouncerQueue.size);\n  // If new debouncers are added while flushing, Set.forEach will ensure\n  // newly added ones are also flushed\n  debouncerQueue.forEach((debouncer) => {\n    try {\n      debouncer.flush();\n    } catch (e) {\n      setTimeout(() => {\n        throw e;\n      });\n    }\n  });\n  return didFlush;\n}\n\nexport const flush = () => {\n  let debouncers;\n  do {\n    debouncers = flushDebouncers();\n  } while (debouncers);\n};\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { setCancelSyntheticClickEvents } from '@polymer/polymer/lib/utils/settings.js';\nimport { usageStatistics } from '@vaadin/vaadin-usage-statistics/vaadin-usage-statistics.js';\nimport { idlePeriod } from './async.js';\nimport { Debouncer, enqueueDebouncer } from './debounce.js';\nimport { DirMixin } from './dir-mixin.js';\n\n// This setting affects the legacy Polymer gestures which get activated\n// once you import any iron component e.g iron-icon.\n// It has to be explicitly disabled to prevent click issues in iOS + VoiceOver\n// for buttons that are based on `[role=button]` e.g vaadin-button.\nsetCancelSyntheticClickEvents(false);\n\nif (!window.Vaadin) {\n  window.Vaadin = {};\n}\n\n/**\n * Array of Vaadin custom element classes that have been finalized.\n */\nif (!window.Vaadin.registrations) {\n  window.Vaadin.registrations = [];\n}\n\nif (!window.Vaadin.developmentModeCallback) {\n  window.Vaadin.developmentModeCallback = {};\n}\n\nwindow.Vaadin.developmentModeCallback['vaadin-usage-statistics'] = function () {\n  usageStatistics();\n};\n\nlet statsJob;\n\nconst registered = new Set();\n\n/**\n * @polymerMixin\n * @mixes DirMixin\n */\nexport const ElementMixin = (superClass) =>\n  class VaadinElementMixin extends DirMixin(superClass) {\n    static get version() {\n      return '24.1.4';\n    }\n\n    /** @protected */\n    static finalize() {\n      super.finalize();\n\n      const { is } = this;\n\n      // Registers a class prototype for telemetry purposes.\n      if (is && !registered.has(is)) {\n        window.Vaadin.registrations.push(this);\n        registered.add(is);\n\n        if (window.Vaadin.developmentModeCallback) {\n          statsJob = Debouncer.debounce(statsJob, idlePeriod, () => {\n            window.Vaadin.developmentModeCallback['vaadin-usage-statistics']();\n          });\n          enqueueDebouncer(statsJob);\n        }\n      }\n    }\n\n    constructor() {\n      super();\n\n      if (document.doctype === null) {\n        console.warn(\n          'Vaadin components require the \"standards mode\" declaration. Please add <!DOCTYPE html> to the HTML document.',\n        );\n      }\n    }\n  };\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\n\nfunction newSplice(index, removed, addedCount) {\n  return {\n    index: index,\n    removed: removed,\n    addedCount: addedCount\n  };\n}\n\nconst EDIT_LEAVE = 0;\nconst EDIT_UPDATE = 1;\nconst EDIT_ADD = 2;\nconst EDIT_DELETE = 3;\n\n// Note: This function is *based* on the computation of the Levenshtein\n// \"edit\" distance. The one change is that \"updates\" are treated as two\n// edits - not one. With Array splices, an update is really a delete\n// followed by an add. By retaining this, we optimize for \"keeping\" the\n// maximum array items in the original array. For example:\n//\n//   'xxxx123' -> '123yyyy'\n//\n// With 1-edit updates, the shortest path would be just to update all seven\n// characters. With 2-edit updates, we delete 4, leave 3, and add 4. This\n// leaves the substring '123' intact.\nfunction calcEditDistances(current, currentStart, currentEnd,\n                            old, oldStart, oldEnd) {\n  // \"Deletion\" columns\n  let rowCount = oldEnd - oldStart + 1;\n  let columnCount = currentEnd - currentStart + 1;\n  let distances = new Array(rowCount);\n\n  // \"Addition\" rows. Initialize null column.\n  for (let i = 0; i < rowCount; i++) {\n    distances[i] = new Array(columnCount);\n    distances[i][0] = i;\n  }\n\n  // Initialize null row\n  for (let j = 0; j < columnCount; j++)\n    distances[0][j] = j;\n\n  for (let i = 1; i < rowCount; i++) {\n    for (let j = 1; j < columnCount; j++) {\n      if (equals(current[currentStart + j - 1], old[oldStart + i - 1]))\n        distances[i][j] = distances[i - 1][j - 1];\n      else {\n        let north = distances[i - 1][j] + 1;\n        let west = distances[i][j - 1] + 1;\n        distances[i][j] = north < west ? north : west;\n      }\n    }\n  }\n\n  return distances;\n}\n\n// This starts at the final weight, and walks \"backward\" by finding\n// the minimum previous weight recursively until the origin of the weight\n// matrix.\nfunction spliceOperationsFromEditDistances(distances) {\n  let i = distances.length - 1;\n  let j = distances[0].length - 1;\n  let current = distances[i][j];\n  let edits = [];\n  while (i > 0 || j > 0) {\n    if (i == 0) {\n      edits.push(EDIT_ADD);\n      j--;\n      continue;\n    }\n    if (j == 0) {\n      edits.push(EDIT_DELETE);\n      i--;\n      continue;\n    }\n    let northWest = distances[i - 1][j - 1];\n    let west = distances[i - 1][j];\n    let north = distances[i][j - 1];\n\n    let min;\n    if (west < north)\n      min = west < northWest ? west : northWest;\n    else\n      min = north < northWest ? north : northWest;\n\n    if (min == northWest) {\n      if (northWest == current) {\n        edits.push(EDIT_LEAVE);\n      } else {\n        edits.push(EDIT_UPDATE);\n        current = northWest;\n      }\n      i--;\n      j--;\n    } else if (min == west) {\n      edits.push(EDIT_DELETE);\n      i--;\n      current = west;\n    } else {\n      edits.push(EDIT_ADD);\n      j--;\n      current = north;\n    }\n  }\n\n  edits.reverse();\n  return edits;\n}\n\n/**\n * Splice Projection functions:\n *\n * A splice map is a representation of how a previous array of items\n * was transformed into a new array of items. Conceptually it is a list of\n * tuples of\n *\n *   <index, removed, addedCount>\n *\n * which are kept in ascending index order of. The tuple represents that at\n * the |index|, |removed| sequence of items were removed, and counting forward\n * from |index|, |addedCount| items were added.\n */\n\n/**\n * Lacking individual splice mutation information, the minimal set of\n * splices can be synthesized given the previous state and final state of an\n * array. The basic approach is to calculate the edit distance matrix and\n * choose the shortest path through it.\n *\n * Complexity: O(l * p)\n *   l: The length of the current array\n *   p: The length of the old array\n *\n * @param {!Array} current The current \"changed\" array for which to\n * calculate splices.\n * @param {number} currentStart Starting index in the `current` array for\n * which splices are calculated.\n * @param {number} currentEnd Ending index in the `current` array for\n * which splices are calculated.\n * @param {!Array} old The original \"unchanged\" array to compare `current`\n * against to determine splices.\n * @param {number} oldStart Starting index in the `old` array for\n * which splices are calculated.\n * @param {number} oldEnd Ending index in the `old` array for\n * which splices are calculated.\n * @return {!Array} Returns an array of splice record objects. Each of these\n * contains: `index` the location where the splice occurred; `removed`\n * the array of removed items from this location; `addedCount` the number\n * of items added at this location.\n */\nfunction calcSplices(current, currentStart, currentEnd,\n                      old, oldStart, oldEnd) {\n  let prefixCount = 0;\n  let suffixCount = 0;\n  let splice;\n\n  let minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart);\n  if (currentStart == 0 && oldStart == 0)\n    prefixCount = sharedPrefix(current, old, minLength);\n\n  if (currentEnd == current.length && oldEnd == old.length)\n    suffixCount = sharedSuffix(current, old, minLength - prefixCount);\n\n  currentStart += prefixCount;\n  oldStart += prefixCount;\n  currentEnd -= suffixCount;\n  oldEnd -= suffixCount;\n\n  if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0)\n    return [];\n\n  if (currentStart == currentEnd) {\n    splice = newSplice(currentStart, [], 0);\n    while (oldStart < oldEnd)\n      splice.removed.push(old[oldStart++]);\n\n    return [ splice ];\n  } else if (oldStart == oldEnd)\n    return [ newSplice(currentStart, [], currentEnd - currentStart) ];\n\n  let ops = spliceOperationsFromEditDistances(\n      calcEditDistances(current, currentStart, currentEnd,\n                             old, oldStart, oldEnd));\n\n  splice = undefined;\n  let splices = [];\n  let index = currentStart;\n  let oldIndex = oldStart;\n  for (let i = 0; i < ops.length; i++) {\n    switch(ops[i]) {\n      case EDIT_LEAVE:\n        if (splice) {\n          splices.push(splice);\n          splice = undefined;\n        }\n\n        index++;\n        oldIndex++;\n        break;\n      case EDIT_UPDATE:\n        if (!splice)\n          splice = newSplice(index, [], 0);\n\n        splice.addedCount++;\n        index++;\n\n        splice.removed.push(old[oldIndex]);\n        oldIndex++;\n        break;\n      case EDIT_ADD:\n        if (!splice)\n          splice = newSplice(index, [], 0);\n\n        splice.addedCount++;\n        index++;\n        break;\n      case EDIT_DELETE:\n        if (!splice)\n          splice = newSplice(index, [], 0);\n\n        splice.removed.push(old[oldIndex]);\n        oldIndex++;\n        break;\n    }\n  }\n\n  if (splice) {\n    splices.push(splice);\n  }\n  return splices;\n}\n\nfunction sharedPrefix(current, old, searchLength) {\n  for (let i = 0; i < searchLength; i++)\n    if (!equals(current[i], old[i]))\n      return i;\n  return searchLength;\n}\n\nfunction sharedSuffix(current, old, searchLength) {\n  let index1 = current.length;\n  let index2 = old.length;\n  let count = 0;\n  while (count < searchLength && equals(current[--index1], old[--index2]))\n    count++;\n\n  return count;\n}\n\n/**\n * Returns an array of splice records indicating the minimum edits required\n * to transform the `previous` array into the `current` array.\n *\n * Splice records are ordered by index and contain the following fields:\n * - `index`: index where edit started\n * - `removed`: array of removed items from this index\n * - `addedCount`: number of items added at this index\n *\n * This function is based on the Levenshtein \"minimum edit distance\"\n * algorithm. Note that updates are treated as removal followed by addition.\n *\n * The worst-case time complexity of this algorithm is `O(l * p)`\n *   l: The length of the current array\n *   p: The length of the previous array\n *\n * However, the worst-case complexity is reduced by an `O(n)` optimization\n * to detect any shared prefix & suffix between the two arrays and only\n * perform the more expensive minimum edit distance calculation over the\n * non-shared portions of the arrays.\n *\n * @function\n * @param {!Array} current The \"changed\" array for which splices will be\n * calculated.\n * @param {!Array} previous The \"unchanged\" original array to compare\n * `current` against to determine the splices.\n * @return {!Array} Returns an array of splice record objects. Each of these\n * contains: `index` the location where the splice occurred; `removed`\n * the array of removed items from this location; `addedCount` the number\n * of items added at this location.\n */\nexport function calculateSplices(current, previous) {\n  return calcSplices(current, 0, current.length, previous, 0,\n                          previous.length);\n}\n\nfunction equals(currentValue, previousValue) {\n  return currentValue === previousValue;\n}\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\n\nimport { calculateSplices } from './array-splice.js';\nimport { microTask } from './async.js';\nimport { wrap } from './wrap.js';\n\n/**\n * Returns true if `node` is a slot element\n * @param {!Node} node Node to test.\n * @return {boolean} Returns true if the given `node` is a slot\n * @private\n */\nfunction isSlot(node) {\n  return (node.localName === 'slot');\n}\n\n/**\n * Class that listens for changes (additions or removals) to\n * \"flattened nodes\" on a given `node`. The list of flattened nodes consists\n * of a node's children and, for any children that are `<slot>` elements,\n * the expanded flattened list of `assignedNodes`.\n * For example, if the observed node has children `<a></a><slot></slot><b></b>`\n * and the `<slot>` has one `<div>` assigned to it, then the flattened\n * nodes list is `<a></a><div></div><b></b>`. If the `<slot>` has other\n * `<slot>` elements assigned to it, these are flattened as well.\n *\n * The provided `callback` is called whenever any change to this list\n * of flattened nodes occurs, where an addition or removal of a node is\n * considered a change. The `callback` is called with one argument, an object\n * containing an array of any `addedNodes` and `removedNodes`.\n *\n * Note: the callback is called asynchronous to any changes\n * at a microtask checkpoint. This is because observation is performed using\n * `MutationObserver` and the `<slot>` element's `slotchange` event which\n * are asynchronous.\n *\n * An example:\n * ```js\n * class TestSelfObserve extends PolymerElement {\n *   static get is() { return 'test-self-observe';}\n *   connectedCallback() {\n *     super.connectedCallback();\n *     this._observer = new FlattenedNodesObserver(this, (info) => {\n *       this.info = info;\n *     });\n *   }\n *   disconnectedCallback() {\n *     super.disconnectedCallback();\n *     this._observer.disconnect();\n *   }\n * }\n * customElements.define(TestSelfObserve.is, TestSelfObserve);\n * ```\n *\n * @summary Class that listens for changes (additions or removals) to\n * \"flattened nodes\" on a given `node`.\n * @implements {PolymerDomApi.ObserveHandle}\n */\nexport let FlattenedNodesObserver = class {\n\n  /**\n   * Returns the list of flattened nodes for the given `node`.\n   * This list consists of a node's children and, for any children\n   * that are `<slot>` elements, the expanded flattened list of `assignedNodes`.\n   * For example, if the observed node has children `<a></a><slot></slot><b></b>`\n   * and the `<slot>` has one `<div>` assigned to it, then the flattened\n   * nodes list is `<a></a><div></div><b></b>`. If the `<slot>` has other\n   * `<slot>` elements assigned to it, these are flattened as well.\n   *\n   * @param {!HTMLElement|!HTMLSlotElement} node The node for which to\n   *      return the list of flattened nodes.\n   * @return {!Array<!Node>} The list of flattened nodes for the given `node`.\n   * @nocollapse See https://github.com/google/closure-compiler/issues/2763\n   */\n  // eslint-disable-next-line\n  static getFlattenedNodes(node) {\n    const wrapped = wrap(node);\n    if (isSlot(node)) {\n      node = /** @type {!HTMLSlotElement} */(node); // eslint-disable-line no-self-assign\n      return wrapped.assignedNodes({flatten: true});\n    } else {\n      return Array.from(wrapped.childNodes).map((node) => {\n        if (isSlot(node)) {\n          node = /** @type {!HTMLSlotElement} */(node); // eslint-disable-line no-self-assign\n          return wrap(node).assignedNodes({flatten: true});\n        } else {\n          return [node];\n        }\n      }).reduce((a, b) => a.concat(b), []);\n    }\n  }\n\n  /**\n   * @param {!HTMLElement} target Node on which to listen for changes.\n   * @param {?function(this: Element, { target: !HTMLElement, addedNodes: !Array<!Element>, removedNodes: !Array<!Element> }):void} callback Function called when there are additions\n   * or removals from the target's list of flattened nodes.\n   */\n  // eslint-disable-next-line\n  constructor(target, callback) {\n    /**\n     * @type {MutationObserver}\n     * @private\n     */\n    this._shadyChildrenObserver = null;\n    /**\n     * @type {MutationObserver}\n     * @private\n     */\n    this._nativeChildrenObserver = null;\n    this._connected = false;\n    /**\n     * @type {!HTMLElement}\n     * @private\n     */\n    this._target = target;\n    this.callback = callback;\n    this._effectiveNodes = [];\n    this._observer = null;\n    this._scheduled = false;\n    /**\n     * @type {function()}\n     * @private\n     */\n    this._boundSchedule = () => {\n      this._schedule();\n    };\n    this.connect();\n    this._schedule();\n  }\n\n  /**\n   * Activates an observer. This method is automatically called when\n   * a `FlattenedNodesObserver` is created. It should only be called to\n   * re-activate an observer that has been deactivated via the `disconnect` method.\n   *\n   * @return {void}\n   */\n  connect() {\n    if (isSlot(this._target)) {\n      this._listenSlots([this._target]);\n    } else if (wrap(this._target).children) {\n      this._listenSlots(\n          /** @type {!NodeList<!Node>} */ (wrap(this._target).children));\n      if (window.ShadyDOM) {\n        this._shadyChildrenObserver =\n          window.ShadyDOM.observeChildren(this._target, (mutations) => {\n            this._processMutations(mutations);\n          });\n      } else {\n        this._nativeChildrenObserver =\n          new MutationObserver((mutations) => {\n            this._processMutations(mutations);\n          });\n        this._nativeChildrenObserver.observe(this._target, {childList: true});\n      }\n    }\n    this._connected = true;\n  }\n\n  /**\n   * Deactivates the flattened nodes observer. After calling this method\n   * the observer callback will not be called when changes to flattened nodes\n   * occur. The `connect` method may be subsequently called to reactivate\n   * the observer.\n   *\n   * @return {void}\n   * @override\n   */\n  disconnect() {\n    if (isSlot(this._target)) {\n      this._unlistenSlots([this._target]);\n    } else if (wrap(this._target).children) {\n      this._unlistenSlots(\n          /** @type {!NodeList<!Node>} */ (wrap(this._target).children));\n      if (window.ShadyDOM && this._shadyChildrenObserver) {\n        window.ShadyDOM.unobserveChildren(this._shadyChildrenObserver);\n        this._shadyChildrenObserver = null;\n      } else if (this._nativeChildrenObserver) {\n        this._nativeChildrenObserver.disconnect();\n        this._nativeChildrenObserver = null;\n      }\n    }\n    this._connected = false;\n  }\n\n  /**\n   * @return {void}\n   * @private\n   */\n  _schedule() {\n    if (!this._scheduled) {\n      this._scheduled = true;\n      microTask.run(() => this.flush());\n    }\n  }\n\n  /**\n   * @param {Array<MutationRecord>} mutations Mutations signaled by the mutation observer\n   * @return {void}\n   * @private\n   */\n  _processMutations(mutations) {\n    this._processSlotMutations(mutations);\n    this.flush();\n  }\n\n  /**\n   * @param {Array<MutationRecord>} mutations Mutations signaled by the mutation observer\n   * @return {void}\n   * @private\n   */\n  _processSlotMutations(mutations) {\n    if (mutations) {\n      for (let i=0; i < mutations.length; i++) {\n        let mutation = mutations[i];\n        if (mutation.addedNodes) {\n          this._listenSlots(mutation.addedNodes);\n        }\n        if (mutation.removedNodes) {\n          this._unlistenSlots(mutation.removedNodes);\n        }\n      }\n    }\n  }\n\n  /**\n   * Flushes the observer causing any pending changes to be immediately\n   * delivered the observer callback. By default these changes are delivered\n   * asynchronously at the next microtask checkpoint.\n   *\n   * @return {boolean} Returns true if any pending changes caused the observer\n   * callback to run.\n   */\n  flush() {\n    if (!this._connected) {\n      return false;\n    }\n    if (window.ShadyDOM) {\n      ShadyDOM.flush();\n    }\n    if (this._nativeChildrenObserver) {\n      this._processSlotMutations(this._nativeChildrenObserver.takeRecords());\n    } else if (this._shadyChildrenObserver) {\n      this._processSlotMutations(this._shadyChildrenObserver.takeRecords());\n    }\n    this._scheduled = false;\n    let info = {\n      target: this._target,\n      addedNodes: [],\n      removedNodes: []\n    };\n    let newNodes = this.constructor.getFlattenedNodes(this._target);\n    let splices = calculateSplices(newNodes,\n      this._effectiveNodes);\n    // process removals\n    for (let i=0, s; (i<splices.length) && (s=splices[i]); i++) {\n      for (let j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) {\n        info.removedNodes.push(n);\n      }\n    }\n    // process adds\n    for (let i=0, s; (i<splices.length) && (s=splices[i]); i++) {\n      for (let j=s.index; j < s.index + s.addedCount; j++) {\n        info.addedNodes.push(newNodes[j]);\n      }\n    }\n    // update cache\n    this._effectiveNodes = newNodes;\n    let didFlush = false;\n    if (info.addedNodes.length || info.removedNodes.length) {\n      didFlush = true;\n      this.callback.call(this._target, info);\n    }\n    return didFlush;\n  }\n\n  /**\n   * @param {!Array<!Node>|!NodeList<!Node>} nodeList Nodes that could change\n   * @return {void}\n   * @private\n   */\n  _listenSlots(nodeList) {\n    for (let i=0; i < nodeList.length; i++) {\n      let n = nodeList[i];\n      if (isSlot(n)) {\n        n.addEventListener('slotchange', this._boundSchedule);\n      }\n    }\n  }\n\n  /**\n   * @param {!Array<!Node>|!NodeList<!Node>} nodeList Nodes that could change\n   * @return {void}\n   * @private\n   */\n  _unlistenSlots(nodeList) {\n    for (let i=0; i < nodeList.length; i++) {\n      let n = nodeList[i];\n      if (isSlot(n)) {\n        n.removeEventListener('slotchange', this._boundSchedule);\n      }\n    }\n  }\n\n};","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * Returns an array of ancestor root nodes for the given node.\n *\n * A root node is either a document node or a document fragment node (Shadow Root).\n * The array is collected by a bottom-up DOM traversing that starts with the given node\n * and involves both the light DOM and ancestor shadow DOM trees.\n *\n * @param {Node} node\n * @return {Node[]}\n */\nexport function getAncestorRootNodes(node) {\n  const result = [];\n\n  while (node) {\n    if (node.nodeType === Node.DOCUMENT_NODE) {\n      result.push(node);\n      break;\n    }\n\n    if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n      result.push(node);\n      node = node.host;\n      continue;\n    }\n\n    if (node.assignedSlot) {\n      node = node.assignedSlot;\n      continue;\n    }\n\n    node = node.parentNode;\n  }\n\n  return result;\n}\n\n/**\n * Traverses the given node and its parents, including those that are across\n * the shadow root boundaries, until it finds a node that matches the selector.\n *\n * @param {string} selector The CSS selector to match against\n * @param {Node} node The starting node for the traversal\n * @return {Node | null} The closest matching element, or null if no match is found\n */\nexport function getClosestElement(selector, node) {\n  if (!node) {\n    return null;\n  }\n\n  return node.closest(selector) || getClosestElement(selector, node.getRootNode().host);\n}\n\n/**\n * Takes a string with values separated by space and returns a set the values\n *\n * @param {string} value\n * @return {Set<string>}\n */\nexport function deserializeAttributeValue(value) {\n  if (!value) {\n    return new Set();\n  }\n\n  return new Set(value.split(' '));\n}\n\n/**\n * Takes a set of string values and returns a string with values separated by space\n *\n * @param {Set<string>} values\n * @return {string}\n */\nexport function serializeAttributeValue(values) {\n  return values ? [...values].join(' ') : '';\n}\n\n/**\n * Adds a value to an attribute containing space-delimited values.\n *\n * @param {HTMLElement} element\n * @param {string} attr\n * @param {string} value\n */\nexport function addValueToAttribute(element, attr, value) {\n  const values = deserializeAttributeValue(element.getAttribute(attr));\n  values.add(value);\n  element.setAttribute(attr, serializeAttributeValue(values));\n}\n\n/**\n * Removes a value from an attribute containing space-delimited values.\n * If the value is the last one, the whole attribute is removed.\n *\n * @param {HTMLElement} element\n * @param {string} attr\n * @param {string} value\n */\nexport function removeValueFromAttribute(element, attr, value) {\n  const values = deserializeAttributeValue(element.getAttribute(attr));\n  values.delete(value);\n  if (values.size === 0) {\n    element.removeAttribute(attr);\n    return;\n  }\n  element.setAttribute(attr, serializeAttributeValue(values));\n}\n\n/**\n * Returns true if the given node is an empty text node, false otherwise.\n *\n * @param {Node} node\n * @return {boolean}\n */\nexport function isEmptyTextNode(node) {\n  return node.nodeType === Node.TEXT_NODE && node.textContent.trim() === '';\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\nlet uniqueId = 0;\n\n/**\n * Resets the unique id counter.\n *\n * @return {void}\n */\nexport function resetUniqueId() {\n  uniqueId = 0;\n}\n\n/**\n * Returns a unique integer id.\n *\n * @return {number}\n */\nexport function generateUniqueId() {\n  // eslint-disable-next-line no-plusplus\n  return uniqueId++;\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { FlattenedNodesObserver } from '@polymer/polymer/lib/utils/flattened-nodes-observer.js';\nimport { isEmptyTextNode } from './dom-utils.js';\nimport { generateUniqueId } from './unique-id-utils.js';\n\n/**\n * A controller for providing content to slot element and observing changes.\n */\nexport class SlotController extends EventTarget {\n  /**\n   * Ensure that every instance has unique ID.\n   *\n   * @param {HTMLElement} host\n   * @param {string} slotName\n   * @return {string}\n   * @protected\n   */\n  static generateId(host, slotName) {\n    const prefix = slotName || 'default';\n    return `${prefix}-${host.localName}-${generateUniqueId()}`;\n  }\n\n  constructor(host, slotName, tagName, config = {}) {\n    super();\n\n    const { initializer, multiple, observe, useUniqueId } = config;\n\n    this.host = host;\n    this.slotName = slotName;\n    this.tagName = tagName;\n    this.observe = typeof observe === 'boolean' ? observe : true;\n    this.multiple = typeof multiple === 'boolean' ? multiple : false;\n    this.slotInitializer = initializer;\n\n    if (multiple) {\n      this.nodes = [];\n    }\n\n    // Only generate the default ID if requested by the controller.\n    if (useUniqueId) {\n      this.defaultId = this.constructor.generateId(host, slotName);\n    }\n  }\n\n  hostConnected() {\n    if (!this.initialized) {\n      if (this.multiple) {\n        this.initMultiple();\n      } else {\n        this.initSingle();\n      }\n\n      if (this.observe) {\n        this.observeSlot();\n      }\n\n      this.initialized = true;\n    }\n  }\n\n  /** @protected */\n  initSingle() {\n    let node = this.getSlotChild();\n\n    if (!node) {\n      node = this.attachDefaultNode();\n      this.initNode(node);\n    } else {\n      this.node = node;\n      this.initAddedNode(node);\n    }\n  }\n\n  /** @protected */\n  initMultiple() {\n    const children = this.getSlotChildren();\n\n    if (children.length === 0) {\n      const defaultNode = this.attachDefaultNode();\n      this.nodes = [defaultNode];\n      this.initNode(defaultNode);\n    } else {\n      this.nodes = children;\n      children.forEach((node) => {\n        this.initAddedNode(node);\n      });\n    }\n  }\n\n  /**\n   * Create and attach default node using the provided tag name, if any.\n   * @return {Node | undefined}\n   * @protected\n   */\n  attachDefaultNode() {\n    const { host, slotName, tagName } = this;\n\n    // Check if the node was created previously and if so, reuse it.\n    let node = this.defaultNode;\n\n    // Tag name is optional, sometimes we don't init default content.\n    if (!node && tagName) {\n      node = document.createElement(tagName);\n      if (node instanceof Element) {\n        if (slotName !== '') {\n          node.setAttribute('slot', slotName);\n        }\n        this.node = node;\n        this.defaultNode = node;\n      }\n    }\n\n    if (node) {\n      host.appendChild(node);\n    }\n\n    return node;\n  }\n\n  /**\n   * Return the list of nodes matching the slot managed by the controller.\n   * @return {Node}\n   */\n  getSlotChildren() {\n    const { slotName } = this;\n    return Array.from(this.host.childNodes).filter((node) => {\n      // Either an element (any slot) or a text node (only un-named slot).\n      return (\n        (node.nodeType === Node.ELEMENT_NODE && node.slot === slotName) ||\n        (node.nodeType === Node.TEXT_NODE && node.textContent.trim() && slotName === '')\n      );\n    });\n  }\n\n  /**\n   * Return a reference to the node managed by the controller.\n   * @return {Node}\n   */\n  getSlotChild() {\n    return this.getSlotChildren()[0];\n  }\n\n  /**\n   * Run `slotInitializer` for the node managed by the controller.\n   *\n   * @param {Node} node\n   * @protected\n   */\n  initNode(node) {\n    const { slotInitializer } = this;\n    // Don't try to bind `this` to initializer (normally it's arrow function).\n    // Instead, pass the host as a first argument to access component's state.\n    if (slotInitializer) {\n      slotInitializer(node, this.host);\n    }\n  }\n\n  /**\n   * Override to initialize the newly added custom node.\n   *\n   * @param {Node} _node\n   * @protected\n   */\n  initCustomNode(_node) {}\n\n  /**\n   * Override to teardown slotted node when it's removed.\n   *\n   * @param {Node} _node\n   * @protected\n   */\n  teardownNode(_node) {}\n\n  /**\n   * Run both `initCustomNode` and `initNode` for a custom slotted node.\n   *\n   * @param {Node} node\n   * @protected\n   */\n  initAddedNode(node) {\n    if (node !== this.defaultNode) {\n      this.initCustomNode(node);\n      this.initNode(node);\n    }\n  }\n\n  /**\n   * Setup the observer to manage slot content changes.\n   * @protected\n   */\n  observeSlot() {\n    const { slotName } = this;\n    const selector = slotName === '' ? 'slot:not([name])' : `slot[name=${slotName}]`;\n    const slot = this.host.shadowRoot.querySelector(selector);\n\n    this.__slotObserver = new FlattenedNodesObserver(slot, (info) => {\n      const current = this.multiple ? this.nodes : [this.node];\n\n      // Calling `slot.assignedNodes()` includes whitespace text nodes in case of default slot:\n      // unlike comment nodes, they are not filtered out. So we need to manually ignore them.\n      const newNodes = info.addedNodes.filter((node) => !isEmptyTextNode(node) && !current.includes(node));\n\n      if (info.removedNodes.length) {\n        info.removedNodes.forEach((node) => {\n          this.teardownNode(node);\n        });\n      }\n\n      if (newNodes && newNodes.length > 0) {\n        if (this.multiple) {\n          // Remove default node if exists\n          if (this.defaultNode) {\n            this.defaultNode.remove();\n          }\n          this.nodes = [...current, ...newNodes].filter((node) => node !== this.defaultNode);\n          newNodes.forEach((node) => {\n            this.initAddedNode(node);\n          });\n        } else {\n          // Remove previous node if exists\n          if (this.node) {\n            this.node.remove();\n          }\n          this.node = newNodes[0];\n          this.initAddedNode(this.node);\n        }\n      }\n    });\n  }\n}\n","/**\n * @license\n * Copyright (c) 2022 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { SlotController } from './slot-controller.js';\n\n/**\n * A controller that manages the slotted tooltip element.\n */\nexport class TooltipController extends SlotController {\n  constructor(host) {\n    // Do not provide slot factory to create tooltip lazily.\n    super(host, 'tooltip');\n\n    this.setTarget(host);\n  }\n\n  /**\n   * Override to initialize the newly added custom tooltip.\n   *\n   * @param {Node} tooltipNode\n   * @protected\n   * @override\n   */\n  initCustomNode(tooltipNode) {\n    tooltipNode.target = this.target;\n\n    if (this.context !== undefined) {\n      tooltipNode.context = this.context;\n    }\n\n    if (this.manual !== undefined) {\n      tooltipNode.manual = this.manual;\n    }\n\n    if (this.opened !== undefined) {\n      tooltipNode.opened = this.opened;\n    }\n\n    if (this.position !== undefined) {\n      tooltipNode._position = this.position;\n    }\n\n    if (this.shouldShow !== undefined) {\n      tooltipNode.shouldShow = this.shouldShow;\n    }\n  }\n\n  /**\n   * Set a context object to be used by generator.\n   * @param {object} context\n   */\n  setContext(context) {\n    this.context = context;\n\n    const tooltipNode = this.node;\n    if (tooltipNode) {\n      tooltipNode.context = context;\n    }\n  }\n\n  /**\n   * Toggle manual state on the slotted tooltip.\n   * @param {boolean} manual\n   */\n  setManual(manual) {\n    this.manual = manual;\n\n    const tooltipNode = this.node;\n    if (tooltipNode) {\n      tooltipNode.manual = manual;\n    }\n  }\n\n  /**\n   * Toggle opened state on the slotted tooltip.\n   * @param {boolean} opened\n   */\n  setOpened(opened) {\n    this.opened = opened;\n\n    const tooltipNode = this.node;\n    if (tooltipNode) {\n      tooltipNode.opened = opened;\n    }\n  }\n\n  /**\n   * Set default position for the slotted tooltip.\n   * This can be overridden by setting the position\n   * using corresponding property or attribute.\n   * @param {string} position\n   */\n  setPosition(position) {\n    this.position = position;\n\n    const tooltipNode = this.node;\n    if (tooltipNode) {\n      tooltipNode._position = position;\n    }\n  }\n\n  /**\n   * Set function used to detect whether to show\n   * the tooltip based on a condition.\n   * @param {Function} shouldShow\n   */\n  setShouldShow(shouldShow) {\n    this.shouldShow = shouldShow;\n\n    const tooltipNode = this.node;\n    if (tooltipNode) {\n      tooltipNode.shouldShow = shouldShow;\n    }\n  }\n\n  /**\n   * Set an HTML element to attach the tooltip to.\n   * @param {HTMLElement} target\n   */\n  setTarget(target) {\n    this.target = target;\n\n    const tooltipNode = this.node;\n    if (tooltipNode) {\n      tooltipNode.target = target;\n    }\n  }\n}\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { css } from 'lit';\n\nexport const buttonStyles = css`\n  :host {\n    display: inline-block;\n    position: relative;\n    outline: none;\n    white-space: nowrap;\n    -webkit-user-select: none;\n    -moz-user-select: none;\n    user-select: none;\n  }\n\n  :host([hidden]) {\n    display: none !important;\n  }\n\n  /* Aligns the button with form fields when placed on the same line.\n  Note, to make it work, the form fields should have the same \"::before\" pseudo-element. */\n  .vaadin-button-container::before {\n    content: '\\\\2003';\n    display: inline-block;\n    width: 0;\n    max-height: 100%;\n  }\n\n  .vaadin-button-container {\n    display: inline-flex;\n    align-items: center;\n    justify-content: center;\n    text-align: center;\n    width: 100%;\n    height: 100%;\n    min-height: inherit;\n    text-shadow: inherit;\n  }\n\n  [part='prefix'],\n  [part='suffix'] {\n    flex: none;\n  }\n\n  [part='label'] {\n    white-space: nowrap;\n    overflow: hidden;\n    text-overflow: ellipsis;\n  }\n\n  @media (forced-colors: active) {\n    :host {\n      outline: 1px solid;\n      outline-offset: -1px;\n    }\n\n    :host([focused]) {\n      outline-width: 2px;\n    }\n\n    :host([disabled]) {\n      outline-color: GrayText;\n    }\n  }\n`;\n\nexport const buttonTemplate = (html) => html`\n  <div class=\"vaadin-button-container\">\n    <span part=\"prefix\" aria-hidden=\"true\">\n      <slot name=\"prefix\"></slot>\n    </span>\n    <span part=\"label\">\n      <slot></slot>\n    </span>\n    <span part=\"suffix\" aria-hidden=\"true\">\n      <slot name=\"suffix\"></slot>\n    </span>\n  </div>\n  <slot name=\"tooltip\"></slot>\n`;\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\n/* eslint-disable @typescript-eslint/no-use-before-define */\n\n/**\n * @fileoverview\n *\n * Module for adding listeners to a node for the following normalized\n * cross-platform \"gesture\" events:\n * - `down` - mouse or touch went down\n * - `up` - mouse or touch went up\n * - `tap` - mouse click or finger tap\n * - `track` - mouse drag or touch move\n *\n * @summary Module for adding cross-platform gesture event listeners.\n */\n\nimport { microTask } from './async.js';\n\nconst passiveTouchGestures = false;\nconst wrap = (node) => node;\n\n// Detect native touch action support\nconst HAS_NATIVE_TA = typeof document.head.style.touchAction === 'string';\nconst GESTURE_KEY = '__polymerGestures';\nconst HANDLED_OBJ = '__polymerGesturesHandled';\nconst TOUCH_ACTION = '__polymerGesturesTouchAction';\n// Radius for tap and track\nconst TAP_DISTANCE = 25;\nconst TRACK_DISTANCE = 5;\n// Number of last N track positions to keep\nconst TRACK_LENGTH = 2;\n\nconst MOUSE_EVENTS = ['mousedown', 'mousemove', 'mouseup', 'click'];\n// An array of bitmask values for mapping MouseEvent.which to MouseEvent.buttons\nconst MOUSE_WHICH_TO_BUTTONS = [0, 1, 4, 2];\nconst MOUSE_HAS_BUTTONS = (function () {\n  try {\n    return new MouseEvent('test', { buttons: 1 }).buttons === 1;\n  } catch (e) {\n    return false;\n  }\n})();\n\n/**\n * @param {string} name Possible mouse event name\n * @return {boolean} true if mouse event, false if not\n */\nfunction isMouseEvent(name) {\n  return MOUSE_EVENTS.indexOf(name) > -1;\n}\n\n/* eslint no-empty: [\"error\", { \"allowEmptyCatch\": true }] */\n// check for passive event listeners\nlet supportsPassive = false;\n(function () {\n  try {\n    const opts = Object.defineProperty({}, 'passive', {\n      // eslint-disable-next-line getter-return\n      get() {\n        supportsPassive = true;\n      },\n    });\n    window.addEventListener('test', null, opts);\n    window.removeEventListener('test', null, opts);\n  } catch (e) {}\n})();\n\n/**\n * Generate settings for event listeners, dependant on `passiveTouchGestures`\n *\n * @param {string} eventName Event name to determine if `{passive}` option is\n *   needed\n * @return {{passive: boolean} | undefined} Options to use for addEventListener\n *   and removeEventListener\n */\nfunction PASSIVE_TOUCH(eventName) {\n  if (isMouseEvent(eventName) || eventName === 'touchend') {\n    return;\n  }\n  if (HAS_NATIVE_TA && supportsPassive && passiveTouchGestures) {\n    return { passive: true };\n  }\n}\n\n// Check for touch-only devices\nconst IS_TOUCH_ONLY = navigator.userAgent.match(/iP(?:[oa]d|hone)|Android/u);\n\n// Defined at https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#enabling-and-disabling-form-controls:-the-disabled-attribute\n/** @type {!Object<boolean>} */\nconst canBeDisabled = {\n  button: true,\n  command: true,\n  fieldset: true,\n  input: true,\n  keygen: true,\n  optgroup: true,\n  option: true,\n  select: true,\n  textarea: true,\n};\n\n/**\n * @param {MouseEvent} ev event to test for left mouse button down\n * @return {boolean} has left mouse button down\n */\nfunction hasLeftMouseButton(ev) {\n  const type = ev.type;\n  // Exit early if the event is not a mouse event\n  if (!isMouseEvent(type)) {\n    return false;\n  }\n  // Ev.button is not reliable for mousemove (0 is overloaded as both left button and no buttons)\n  // instead we use ev.buttons (bitmask of buttons) or fall back to ev.which (deprecated, 0 for no buttons, 1 for left button)\n  if (type === 'mousemove') {\n    // Allow undefined for testing events\n    let buttons = ev.buttons === undefined ? 1 : ev.buttons;\n    if (ev instanceof window.MouseEvent && !MOUSE_HAS_BUTTONS) {\n      buttons = MOUSE_WHICH_TO_BUTTONS[ev.which] || 0;\n    }\n    // Buttons is a bitmask, check that the left button bit is set (1)\n    return Boolean(buttons & 1);\n  }\n  // Allow undefined for testing events\n  const button = ev.button === undefined ? 0 : ev.button;\n  // Ev.button is 0 in mousedown/mouseup/click for left button activation\n  return button === 0;\n}\n\nfunction isSyntheticClick(ev) {\n  if (ev.type === 'click') {\n    // Ev.detail is 0 for HTMLElement.click in most browsers\n    if (ev.detail === 0) {\n      return true;\n    }\n    // In the worst case, check that the x/y position of the click is within\n    // the bounding box of the target of the event\n    // Thanks IE 10 >:(\n    const t = _findOriginalTarget(ev);\n    // Make sure the target of the event is an element so we can use getBoundingClientRect,\n    // if not, just assume it is a synthetic click\n    if (!t.nodeType || /** @type {Element} */ (t).nodeType !== Node.ELEMENT_NODE) {\n      return true;\n    }\n    const bcr = /** @type {Element} */ (t).getBoundingClientRect();\n    // Use page x/y to account for scrolling\n    const x = ev.pageX,\n      y = ev.pageY;\n    // Ev is a synthetic click if the position is outside the bounding box of the target\n    return !(x >= bcr.left && x <= bcr.right && y >= bcr.top && y <= bcr.bottom);\n  }\n  return false;\n}\n\nconst POINTERSTATE = {\n  mouse: {\n    target: null,\n    mouseIgnoreJob: null,\n  },\n  touch: {\n    x: 0,\n    y: 0,\n    id: -1,\n    scrollDecided: false,\n  },\n};\n\nfunction firstTouchAction(ev) {\n  let ta = 'auto';\n  const path = getComposedPath(ev);\n  for (let i = 0, n; i < path.length; i++) {\n    n = path[i];\n    if (n[TOUCH_ACTION]) {\n      ta = n[TOUCH_ACTION];\n      break;\n    }\n  }\n  return ta;\n}\n\nfunction trackDocument(stateObj, movefn, upfn) {\n  stateObj.movefn = movefn;\n  stateObj.upfn = upfn;\n  document.addEventListener('mousemove', movefn);\n  document.addEventListener('mouseup', upfn);\n}\n\nfunction untrackDocument(stateObj) {\n  document.removeEventListener('mousemove', stateObj.movefn);\n  document.removeEventListener('mouseup', stateObj.upfn);\n  stateObj.movefn = null;\n  stateObj.upfn = null;\n}\n\n/**\n * Returns the composedPath for the given event.\n * @param {Event} event to process\n * @return {!Array<!EventTarget>} Path of the event\n */\nconst getComposedPath =\n  window.ShadyDOM && window.ShadyDOM.noPatch\n    ? window.ShadyDOM.composedPath\n    : (event) => (event.composedPath && event.composedPath()) || [];\n\n/** @type {!Object<string, !GestureRecognizer>} */\nexport const gestures = {};\n\n/** @type {!Array<!GestureRecognizer>} */\nexport const recognizers = [];\n\n/**\n * Finds the element rendered on the screen at the provided coordinates.\n *\n * Similar to `document.elementFromPoint`, but pierces through\n * shadow roots.\n *\n * @param {number} x Horizontal pixel coordinate\n * @param {number} y Vertical pixel coordinate\n * @return {Element} Returns the deepest shadowRoot inclusive element\n * found at the screen position given.\n */\nexport function deepTargetFind(x, y) {\n  let node = document.elementFromPoint(x, y);\n  let next = node;\n  // This code path is only taken when native ShadowDOM is used\n  // if there is a shadowroot, it may have a node at x/y\n  // if there is not a shadowroot, exit the loop\n  while (next && next.shadowRoot && !window.ShadyDOM) {\n    // If there is a node at x/y in the shadowroot, look deeper\n    const oldNext = next;\n    next = next.shadowRoot.elementFromPoint(x, y);\n    // On Safari, elementFromPoint may return the shadowRoot host\n    if (oldNext === next) {\n      break;\n    }\n    if (next) {\n      node = next;\n    }\n  }\n  return node;\n}\n\n/**\n * A cheaper check than ev.composedPath()[0];\n *\n * @private\n * @param {Event|Touch} ev Event.\n * @return {EventTarget} Returns the event target.\n */\nfunction _findOriginalTarget(ev) {\n  const path = getComposedPath(/** @type {?Event} */ (ev));\n  // It shouldn't be, but sometimes path is empty (window on Safari).\n  return path.length > 0 ? path[0] : ev.target;\n}\n\n/**\n * @private\n * @param {Event} ev Event.\n * @return {void}\n */\nfunction _handleNative(ev) {\n  const type = ev.type;\n  const node = ev.currentTarget;\n  const gobj = node[GESTURE_KEY];\n  if (!gobj) {\n    return;\n  }\n  const gs = gobj[type];\n  if (!gs) {\n    return;\n  }\n  if (!ev[HANDLED_OBJ]) {\n    ev[HANDLED_OBJ] = {};\n    if (type.startsWith('touch')) {\n      const t = ev.changedTouches[0];\n      if (type === 'touchstart') {\n        // Only handle the first finger\n        if (ev.touches.length === 1) {\n          POINTERSTATE.touch.id = t.identifier;\n        }\n      }\n      if (POINTERSTATE.touch.id !== t.identifier) {\n        return;\n      }\n      if (!HAS_NATIVE_TA) {\n        if (type === 'touchstart' || type === 'touchmove') {\n          _handleTouchAction(ev);\n        }\n      }\n    }\n  }\n  const handled = ev[HANDLED_OBJ];\n  // Used to ignore synthetic mouse events\n  if (handled.skip) {\n    return;\n  }\n  // Reset recognizer state\n  for (let i = 0, r; i < recognizers.length; i++) {\n    r = recognizers[i];\n    if (gs[r.name] && !handled[r.name]) {\n      if (r.flow && r.flow.start.indexOf(ev.type) > -1 && r.reset) {\n        r.reset();\n      }\n    }\n  }\n  // Enforce gesture recognizer order\n  for (let i = 0, r; i < recognizers.length; i++) {\n    r = recognizers[i];\n    if (gs[r.name] && !handled[r.name]) {\n      handled[r.name] = true;\n      r[type](ev);\n    }\n  }\n}\n\n/**\n * @private\n * @param {TouchEvent} ev Event.\n * @return {void}\n */\nfunction _handleTouchAction(ev) {\n  const t = ev.changedTouches[0];\n  const type = ev.type;\n  if (type === 'touchstart') {\n    POINTERSTATE.touch.x = t.clientX;\n    POINTERSTATE.touch.y = t.clientY;\n    POINTERSTATE.touch.scrollDecided = false;\n  } else if (type === 'touchmove') {\n    if (POINTERSTATE.touch.scrollDecided) {\n      return;\n    }\n    POINTERSTATE.touch.scrollDecided = true;\n    const ta = firstTouchAction(ev);\n    let shouldPrevent = false;\n    const dx = Math.abs(POINTERSTATE.touch.x - t.clientX);\n    const dy = Math.abs(POINTERSTATE.touch.y - t.clientY);\n    if (!ev.cancelable) {\n      // Scrolling is happening\n    } else if (ta === 'none') {\n      shouldPrevent = true;\n    } else if (ta === 'pan-x') {\n      shouldPrevent = dy > dx;\n    } else if (ta === 'pan-y') {\n      shouldPrevent = dx > dy;\n    }\n    if (shouldPrevent) {\n      ev.preventDefault();\n    } else {\n      prevent('track');\n    }\n  }\n}\n\n/**\n * Adds an event listener to a node for the given gesture type.\n *\n * @param {!EventTarget} node Node to add listener on\n * @param {string} evType Gesture type: `down`, `up`, `track`, or `tap`\n * @param {!function(!Event):void} handler Event listener function to call\n * @return {boolean} Returns true if a gesture event listener was added.\n */\nexport function addListener(node, evType, handler) {\n  if (gestures[evType]) {\n    _add(node, evType, handler);\n    return true;\n  }\n  return false;\n}\n\n/**\n * Removes an event listener from a node for the given gesture type.\n *\n * @param {!EventTarget} node Node to remove listener from\n * @param {string} evType Gesture type: `down`, `up`, `track`, or `tap`\n * @param {!function(!Event):void} handler Event listener function previously passed to\n *  `addListener`.\n * @return {boolean} Returns true if a gesture event listener was removed.\n */\nexport function removeListener(node, evType, handler) {\n  if (gestures[evType]) {\n    _remove(node, evType, handler);\n    return true;\n  }\n  return false;\n}\n\n/**\n * Automate the event listeners for the native events\n *\n * @private\n * @param {!EventTarget} node Node on which to add the event.\n * @param {string} evType Event type to add.\n * @param {function(!Event)} handler Event handler function.\n * @return {void}\n */\nfunction _add(node, evType, handler) {\n  const recognizer = gestures[evType];\n  const deps = recognizer.deps;\n  const name = recognizer.name;\n  let gobj = node[GESTURE_KEY];\n  if (!gobj) {\n    node[GESTURE_KEY] = gobj = {};\n  }\n  for (let i = 0, dep, gd; i < deps.length; i++) {\n    dep = deps[i];\n    // Don't add mouse handlers on iOS because they cause gray selection overlays\n    if (IS_TOUCH_ONLY && isMouseEvent(dep) && dep !== 'click') {\n      continue;\n    }\n    gd = gobj[dep];\n    if (!gd) {\n      gobj[dep] = gd = { _count: 0 };\n    }\n    if (gd._count === 0) {\n      node.addEventListener(dep, _handleNative, PASSIVE_TOUCH(dep));\n    }\n    gd[name] = (gd[name] || 0) + 1;\n    gd._count = (gd._count || 0) + 1;\n  }\n  node.addEventListener(evType, handler);\n  if (recognizer.touchAction) {\n    setTouchAction(node, recognizer.touchAction);\n  }\n}\n\n/**\n * Automate event listener removal for native events\n *\n * @private\n * @param {!EventTarget} node Node on which to remove the event.\n * @param {string} evType Event type to remove.\n * @param {function(!Event): void} handler Event handler function.\n * @return {void}\n */\nfunction _remove(node, evType, handler) {\n  const recognizer = gestures[evType];\n  const deps = recognizer.deps;\n  const name = recognizer.name;\n  const gobj = node[GESTURE_KEY];\n  if (gobj) {\n    for (let i = 0, dep, gd; i < deps.length; i++) {\n      dep = deps[i];\n      gd = gobj[dep];\n      if (gd && gd[name]) {\n        gd[name] = (gd[name] || 1) - 1;\n        gd._count = (gd._count || 1) - 1;\n        if (gd._count === 0) {\n          node.removeEventListener(dep, _handleNative, PASSIVE_TOUCH(dep));\n        }\n      }\n    }\n  }\n  node.removeEventListener(evType, handler);\n}\n\n/**\n * Registers a new gesture event recognizer for adding new custom\n * gesture event types.\n *\n * @param {!GestureRecognizer} recog Gesture recognizer descriptor\n * @return {void}\n */\nexport function register(recog) {\n  recognizers.push(recog);\n  recog.emits.forEach((emit) => {\n    gestures[emit] = recog;\n  });\n}\n\n/**\n * @private\n * @param {string} evName Event name.\n * @return {Object} Returns the gesture for the given event name.\n */\nfunction _findRecognizerByEvent(evName) {\n  for (let i = 0, r; i < recognizers.length; i++) {\n    r = recognizers[i];\n    for (let j = 0, n; j < r.emits.length; j++) {\n      n = r.emits[j];\n      if (n === evName) {\n        return r;\n      }\n    }\n  }\n  return null;\n}\n\n/**\n * Sets scrolling direction on node.\n *\n * This value is checked on first move, thus it should be called prior to\n * adding event listeners.\n *\n * @param {!EventTarget} node Node to set touch action setting on\n * @param {string} value Touch action value\n * @return {void}\n */\nexport function setTouchAction(node, value) {\n  if (HAS_NATIVE_TA && node instanceof HTMLElement) {\n    // NOTE: add touchAction async so that events can be added in\n    // custom element constructors. Otherwise we run afoul of custom\n    // elements restriction against settings attributes (style) in the\n    // constructor.\n    microTask.run(() => {\n      node.style.touchAction = value;\n    });\n  }\n  node[TOUCH_ACTION] = value;\n}\n\n/**\n * Dispatches an event on the `target` element of `type` with the given\n * `detail`.\n * @private\n * @param {!EventTarget} target The element on which to fire an event.\n * @param {string} type The type of event to fire.\n * @param {!Object=} detail The detail object to populate on the event.\n * @return {void}\n */\nfunction _fire(target, type, detail) {\n  const ev = new Event(type, { bubbles: true, cancelable: true, composed: true });\n  ev.detail = detail;\n  wrap(/** @type {!Node} */ (target)).dispatchEvent(ev);\n  // Forward `preventDefault` in a clean way\n  if (ev.defaultPrevented) {\n    const preventer = detail.preventer || detail.sourceEvent;\n    if (preventer && preventer.preventDefault) {\n      preventer.preventDefault();\n    }\n  }\n}\n\n/**\n * Prevents the dispatch and default action of the given event name.\n *\n * @param {string} evName Event name.\n * @return {void}\n */\nexport function prevent(evName) {\n  const recognizer = _findRecognizerByEvent(evName);\n  if (recognizer.info) {\n    recognizer.info.prevent = true;\n  }\n}\n\nregister({\n  name: 'downup',\n  deps: ['mousedown', 'touchstart', 'touchend'],\n  flow: {\n    start: ['mousedown', 'touchstart'],\n    end: ['mouseup', 'touchend'],\n  },\n  emits: ['down', 'up'],\n\n  info: {\n    movefn: null,\n    upfn: null,\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @return {void}\n   */\n  reset() {\n    untrackDocument(this.info);\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {MouseEvent} e\n   * @return {void}\n   */\n  mousedown(e) {\n    if (!hasLeftMouseButton(e)) {\n      return;\n    }\n    const t = _findOriginalTarget(e);\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const self = this;\n    const movefn = (e) => {\n      if (!hasLeftMouseButton(e)) {\n        downupFire('up', t, e);\n        untrackDocument(self.info);\n      }\n    };\n    const upfn = (e) => {\n      if (hasLeftMouseButton(e)) {\n        downupFire('up', t, e);\n      }\n      untrackDocument(self.info);\n    };\n    trackDocument(this.info, movefn, upfn);\n    downupFire('down', t, e);\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {TouchEvent} e\n   * @return {void}\n   */\n  touchstart(e) {\n    downupFire('down', _findOriginalTarget(e), e.changedTouches[0], e);\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {TouchEvent} e\n   * @return {void}\n   */\n  touchend(e) {\n    downupFire('up', _findOriginalTarget(e), e.changedTouches[0], e);\n  },\n});\n\n/**\n * @param {string} type\n * @param {EventTarget} target\n * @param {Event|Touch} event\n * @param {Event=} preventer\n * @return {void}\n */\nfunction downupFire(type, target, event, preventer) {\n  if (!target) {\n    return;\n  }\n  _fire(target, type, {\n    x: event.clientX,\n    y: event.clientY,\n    sourceEvent: event,\n    preventer,\n    prevent(e) {\n      return prevent(e);\n    },\n  });\n}\n\nregister({\n  name: 'track',\n  touchAction: 'none',\n  deps: ['mousedown', 'touchstart', 'touchmove', 'touchend'],\n  flow: {\n    start: ['mousedown', 'touchstart'],\n    end: ['mouseup', 'touchend'],\n  },\n  emits: ['track'],\n\n  info: {\n    x: 0,\n    y: 0,\n    state: 'start',\n    started: false,\n    moves: [],\n    /** @this {GestureInfo} */\n    addMove(move) {\n      if (this.moves.length > TRACK_LENGTH) {\n        this.moves.shift();\n      }\n      this.moves.push(move);\n    },\n    movefn: null,\n    upfn: null,\n    prevent: false,\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @return {void}\n   */\n  reset() {\n    this.info.state = 'start';\n    this.info.started = false;\n    this.info.moves = [];\n    this.info.x = 0;\n    this.info.y = 0;\n    this.info.prevent = false;\n    untrackDocument(this.info);\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {MouseEvent} e\n   * @return {void}\n   */\n  mousedown(e) {\n    if (!hasLeftMouseButton(e)) {\n      return;\n    }\n    const t = _findOriginalTarget(e);\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const self = this;\n    const movefn = (e) => {\n      const x = e.clientX,\n        y = e.clientY;\n      if (trackHasMovedEnough(self.info, x, y)) {\n        // First move is 'start', subsequent moves are 'move', mouseup is 'end'\n        self.info.state = self.info.started ? (e.type === 'mouseup' ? 'end' : 'track') : 'start';\n        if (self.info.state === 'start') {\n          // If and only if tracking, always prevent tap\n          prevent('tap');\n        }\n        self.info.addMove({ x, y });\n        if (!hasLeftMouseButton(e)) {\n          // Always fire \"end\"\n          self.info.state = 'end';\n          untrackDocument(self.info);\n        }\n        if (t) {\n          trackFire(self.info, t, e);\n        }\n        self.info.started = true;\n      }\n    };\n    const upfn = (e) => {\n      if (self.info.started) {\n        movefn(e);\n      }\n\n      // Remove the temporary listeners\n      untrackDocument(self.info);\n    };\n    // Add temporary document listeners as mouse retargets\n    trackDocument(this.info, movefn, upfn);\n    this.info.x = e.clientX;\n    this.info.y = e.clientY;\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {TouchEvent} e\n   * @return {void}\n   */\n  touchstart(e) {\n    const ct = e.changedTouches[0];\n    this.info.x = ct.clientX;\n    this.info.y = ct.clientY;\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {TouchEvent} e\n   * @return {void}\n   */\n  touchmove(e) {\n    const t = _findOriginalTarget(e);\n    const ct = e.changedTouches[0];\n    const x = ct.clientX,\n      y = ct.clientY;\n    if (trackHasMovedEnough(this.info, x, y)) {\n      if (this.info.state === 'start') {\n        // If and only if tracking, always prevent tap\n        prevent('tap');\n      }\n      this.info.addMove({ x, y });\n      trackFire(this.info, t, ct);\n      this.info.state = 'track';\n      this.info.started = true;\n    }\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {TouchEvent} e\n   * @return {void}\n   */\n  touchend(e) {\n    const t = _findOriginalTarget(e);\n    const ct = e.changedTouches[0];\n    // Only trackend if track was started and not aborted\n    if (this.info.started) {\n      // Reset started state on up\n      this.info.state = 'end';\n      this.info.addMove({ x: ct.clientX, y: ct.clientY });\n      trackFire(this.info, t, ct);\n    }\n  },\n});\n\n/**\n * @param {!GestureInfo} info\n * @param {number} x\n * @param {number} y\n * @return {boolean}\n */\nfunction trackHasMovedEnough(info, x, y) {\n  if (info.prevent) {\n    return false;\n  }\n  if (info.started) {\n    return true;\n  }\n  const dx = Math.abs(info.x - x);\n  const dy = Math.abs(info.y - y);\n  return dx >= TRACK_DISTANCE || dy >= TRACK_DISTANCE;\n}\n\n/**\n * @param {!GestureInfo} info\n * @param {?EventTarget} target\n * @param {Touch} touch\n * @return {void}\n */\nfunction trackFire(info, target, touch) {\n  if (!target) {\n    return;\n  }\n  const secondlast = info.moves[info.moves.length - 2];\n  const lastmove = info.moves[info.moves.length - 1];\n  const dx = lastmove.x - info.x;\n  const dy = lastmove.y - info.y;\n  let ddx,\n    ddy = 0;\n  if (secondlast) {\n    ddx = lastmove.x - secondlast.x;\n    ddy = lastmove.y - secondlast.y;\n  }\n  _fire(target, 'track', {\n    state: info.state,\n    x: touch.clientX,\n    y: touch.clientY,\n    dx,\n    dy,\n    ddx,\n    ddy,\n    sourceEvent: touch,\n    hover() {\n      return deepTargetFind(touch.clientX, touch.clientY);\n    },\n  });\n}\n\nregister({\n  name: 'tap',\n  deps: ['mousedown', 'click', 'touchstart', 'touchend'],\n  flow: {\n    start: ['mousedown', 'touchstart'],\n    end: ['click', 'touchend'],\n  },\n  emits: ['tap'],\n  info: {\n    x: NaN,\n    y: NaN,\n    prevent: false,\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @return {void}\n   */\n  reset() {\n    this.info.x = NaN;\n    this.info.y = NaN;\n    this.info.prevent = false;\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {MouseEvent} e\n   * @return {void}\n   */\n  mousedown(e) {\n    if (hasLeftMouseButton(e)) {\n      this.info.x = e.clientX;\n      this.info.y = e.clientY;\n    }\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {MouseEvent} e\n   * @return {void}\n   */\n  click(e) {\n    if (hasLeftMouseButton(e)) {\n      trackForward(this.info, e);\n    }\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {TouchEvent} e\n   * @return {void}\n   */\n  touchstart(e) {\n    const touch = e.changedTouches[0];\n    this.info.x = touch.clientX;\n    this.info.y = touch.clientY;\n  },\n\n  /**\n   * @this {GestureRecognizer}\n   * @param {TouchEvent} e\n   * @return {void}\n   */\n  touchend(e) {\n    trackForward(this.info, e.changedTouches[0], e);\n  },\n});\n\n/**\n * @param {!GestureInfo} info\n * @param {Event | Touch} e\n * @param {Event=} preventer\n * @return {void}\n */\nfunction trackForward(info, e, preventer) {\n  const dx = Math.abs(e.clientX - info.x);\n  const dy = Math.abs(e.clientY - info.y);\n  // Find original target from `preventer` for TouchEvents, or `e` for MouseEvents\n  const t = _findOriginalTarget(preventer || e);\n  if (!t || (canBeDisabled[/** @type {!HTMLElement} */ (t).localName] && t.hasAttribute('disabled'))) {\n    return;\n  }\n  // Dx,dy can be NaN if `click` has been simulated and there was no `down` for `start`\n  if (isNaN(dx) || isNaN(dy) || (dx <= TAP_DISTANCE && dy <= TAP_DISTANCE) || isSyntheticClick(e)) {\n    // Prevent taps from being generated if an event has canceled them\n    if (!info.prevent) {\n      _fire(t, 'tap', {\n        x: e.clientX,\n        y: e.clientY,\n        sourceEvent: e,\n        preventer,\n      });\n    }\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\n\n/**\n * A mixin to provide disabled property for field components.\n *\n * @polymerMixin\n */\nexport const DisabledMixin = dedupingMixin(\n  (superclass) =>\n    class DisabledMixinClass extends superclass {\n      static get properties() {\n        return {\n          /**\n           * If true, the user cannot interact with this element.\n           */\n          disabled: {\n            type: Boolean,\n            value: false,\n            observer: '_disabledChanged',\n            reflectToAttribute: true,\n          },\n        };\n      }\n\n      /**\n       * @param {boolean} disabled\n       * @protected\n       */\n      _disabledChanged(disabled) {\n        this._setAriaDisabled(disabled);\n      }\n\n      /**\n       * @param {boolean} disabled\n       * @protected\n       */\n      _setAriaDisabled(disabled) {\n        if (disabled) {\n          this.setAttribute('aria-disabled', 'true');\n        } else {\n          this.removeAttribute('aria-disabled');\n        }\n      }\n\n      /**\n       * Overrides the default element `click` method in order to prevent\n       * firing the `click` event when the element is disabled.\n       * @protected\n       * @override\n       */\n      click() {\n        if (!this.disabled) {\n          super.click();\n        }\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\n\n/**\n * A mixin that manages keyboard handling.\n * The mixin subscribes to the keyboard events while an actual implementation\n * for the event handlers is left to the client (a component or another mixin).\n *\n * @polymerMixin\n */\nexport const KeyboardMixin = dedupingMixin(\n  (superclass) =>\n    class KeyboardMixinClass extends superclass {\n      /** @protected */\n      ready() {\n        super.ready();\n\n        this.addEventListener('keydown', (event) => {\n          this._onKeyDown(event);\n        });\n\n        this.addEventListener('keyup', (event) => {\n          this._onKeyUp(event);\n        });\n      }\n\n      /**\n       * A handler for the `keydown` event. By default, it calls\n       * separate methods for handling \"Enter\" and \"Escape\" keys.\n       * Override the method to implement your own behavior.\n       *\n       * @param {KeyboardEvent} event\n       * @protected\n       */\n      _onKeyDown(event) {\n        switch (event.key) {\n          case 'Enter':\n            this._onEnter(event);\n            break;\n          case 'Escape':\n            this._onEscape(event);\n            break;\n          default:\n            break;\n        }\n      }\n\n      /**\n       * A handler for the `keyup` event. By default, it does nothing.\n       * Override the method to implement your own behavior.\n       *\n       * @param {KeyboardEvent} _event\n       * @protected\n       */\n      _onKeyUp(_event) {\n        // To be implemented.\n      }\n\n      /**\n       * A handler for the \"Enter\" key. By default, it does nothing.\n       * Override the method to implement your own behavior.\n       *\n       * @param {KeyboardEvent} _event\n       * @protected\n       */\n      _onEnter(_event) {\n        // To be implemented.\n      }\n\n      /**\n       * A handler for the \"Escape\" key. By default, it does nothing.\n       * Override the method to implement your own behavior.\n       *\n       * @param {KeyboardEvent} _event\n       * @protected\n       */\n      _onEscape(_event) {\n        // To be implemented.\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { addListener } from '@vaadin/component-base/src/gestures.js';\nimport { DisabledMixin } from './disabled-mixin.js';\nimport { KeyboardMixin } from './keyboard-mixin.js';\n\n/**\n * A mixin to toggle the `active` attribute.\n *\n * The attribute is set whenever the user activates the element by a pointer\n * or presses an activation key on the element from the keyboard.\n *\n * The attribute is removed as soon as the element is deactivated\n * by the pointer or by releasing the activation key.\n *\n * @polymerMixin\n */\nexport const ActiveMixin = (superclass) =>\n  class ActiveMixinClass extends DisabledMixin(KeyboardMixin(superclass)) {\n    /**\n     * An array of activation keys.\n     *\n     * See possible values here:\n     * https://developer.mozilla.org/ru/docs/Web/API/KeyboardEvent/key/Key_Values\n     *\n     * @protected\n     * @return {!Array<!string>}\n     */\n    get _activeKeys() {\n      return [' '];\n    }\n\n    /** @protected */\n    ready() {\n      super.ready();\n\n      addListener(this, 'down', (event) => {\n        if (this._shouldSetActive(event)) {\n          this._setActive(true);\n        }\n      });\n\n      addListener(this, 'up', () => {\n        this._setActive(false);\n      });\n    }\n\n    /** @protected */\n    disconnectedCallback() {\n      super.disconnectedCallback();\n\n      // When the element is disconnecting from the DOM at the moment being active,\n      // the `active` attribute needs to be manually removed from the element.\n      // Otherwise, it will preserve on the element until the element is activated once again.\n      // The case reproduces for `<vaadin-date-picker>` when closing on `Cancel` or `Today` click.\n      this._setActive(false);\n    }\n\n    /**\n     * @param {KeyboardEvent | MouseEvent} _event\n     * @protected\n     */\n    _shouldSetActive(_event) {\n      return !this.disabled;\n    }\n\n    /**\n     * Sets the `active` attribute on the element if an activation key is pressed.\n     *\n     * @param {KeyboardEvent} event\n     * @protected\n     * @override\n     */\n    _onKeyDown(event) {\n      super._onKeyDown(event);\n\n      if (this._shouldSetActive(event) && this._activeKeys.includes(event.key)) {\n        this._setActive(true);\n\n        // Element can become hidden before the `keyup` event, e.g. on button click.\n        // Use document listener to ensure `active` attribute is removed correctly.\n        document.addEventListener(\n          'keyup',\n          (e) => {\n            if (this._activeKeys.includes(e.key)) {\n              this._setActive(false);\n            }\n          },\n          { once: true },\n        );\n      }\n    }\n\n    /**\n     * Toggles the `active` attribute on the element.\n     *\n     * @param {boolean} active\n     * @protected\n     */\n    _setActive(active) {\n      this.toggleAttribute('active', active);\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\nimport { isKeyboardActive } from './focus-utils.js';\n\n/**\n * A mixin to handle `focused` and `focus-ring` attributes based on focus.\n *\n * @polymerMixin\n */\nexport const FocusMixin = dedupingMixin(\n  (superclass) =>\n    class FocusMixinClass extends superclass {\n      /**\n       * @protected\n       * @return {boolean}\n       */\n      get _keyboardActive() {\n        return isKeyboardActive();\n      }\n\n      /** @protected */\n      ready() {\n        this.addEventListener('focusin', (e) => {\n          if (this._shouldSetFocus(e)) {\n            this._setFocused(true);\n          }\n        });\n\n        this.addEventListener('focusout', (e) => {\n          if (this._shouldRemoveFocus(e)) {\n            this._setFocused(false);\n          }\n        });\n\n        // In super.ready() other 'focusin' and 'focusout' listeners might be\n        // added, so we call it after our own ones to ensure they execute first.\n        // Issue to watch out: when incorrect, <vaadin-combo-box> refocuses the\n        // input field on iOS after \"Done\" is pressed.\n        super.ready();\n      }\n\n      /** @protected */\n      disconnectedCallback() {\n        super.disconnectedCallback();\n\n        // In non-Chrome browsers, blur does not fire on the element when it is disconnected.\n        // reproducible in `<vaadin-date-picker>` when closing on `Cancel` or `Today` click.\n        if (this.hasAttribute('focused')) {\n          this._setFocused(false);\n        }\n      }\n\n      /**\n       * Override to change how focused and focus-ring attributes are set.\n       *\n       * @param {boolean} focused\n       * @protected\n       */\n      _setFocused(focused) {\n        this.toggleAttribute('focused', focused);\n\n        // Focus-ring is true when the element was focused from the keyboard.\n        // Focus Ring [A11ycasts]: https://youtu.be/ilj2P5-5CjI\n        this.toggleAttribute('focus-ring', focused && this._keyboardActive);\n      }\n\n      /**\n       * Override to define if the field receives focus based on the event.\n       *\n       * @param {FocusEvent} _event\n       * @return {boolean}\n       * @protected\n       */\n      _shouldSetFocus(_event) {\n        return true;\n      }\n\n      /**\n       * Override to define if the field loses focus based on the event.\n       *\n       * @param {FocusEvent} _event\n       * @return {boolean}\n       * @protected\n       */\n      _shouldRemoveFocus(_event) {\n        return true;\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { DisabledMixin } from './disabled-mixin.js';\n\n/**\n * A mixin to toggle the `tabindex` attribute.\n *\n * The attribute is set to -1 whenever the user disables the element\n * and restored with the last known value once the element is enabled.\n *\n * @polymerMixin\n * @mixes DisabledMixin\n */\nexport const TabindexMixin = (superclass) =>\n  class TabindexMixinClass extends DisabledMixin(superclass) {\n    static get properties() {\n      return {\n        /**\n         * Indicates whether the element can be focused and where it participates in sequential keyboard navigation.\n         *\n         * @protected\n         */\n        tabindex: {\n          type: Number,\n          reflectToAttribute: true,\n          observer: '_tabindexChanged',\n        },\n\n        /**\n         * Stores the last known tabindex since the element has been disabled.\n         *\n         * @protected\n         */\n        _lastTabIndex: {\n          type: Number,\n        },\n      };\n    }\n\n    /**\n     * When the element gets disabled, the observer saves the last known tabindex\n     * and makes the element not focusable by setting tabindex to -1.\n     * As soon as the element gets enabled, the observer restores the last known tabindex\n     * so that the element can be focusable again.\n     *\n     * @protected\n     * @override\n     */\n    _disabledChanged(disabled, oldDisabled) {\n      super._disabledChanged(disabled, oldDisabled);\n\n      if (disabled) {\n        if (this.tabindex !== undefined) {\n          this._lastTabIndex = this.tabindex;\n        }\n        this.tabindex = -1;\n      } else if (oldDisabled) {\n        this.tabindex = this._lastTabIndex;\n      }\n    }\n\n    /**\n     * When the user has changed tabindex while the element is disabled,\n     * the observer reverts tabindex to -1 and rather saves the new tabindex value to apply it later.\n     * The new value will be applied as soon as the element becomes enabled.\n     *\n     * @protected\n     */\n    _tabindexChanged(tabindex) {\n      if (this.disabled && tabindex !== -1) {\n        this._lastTabIndex = tabindex;\n        this.tabindex = -1;\n      }\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { ActiveMixin } from '@vaadin/a11y-base/src/active-mixin.js';\nimport { FocusMixin } from '@vaadin/a11y-base/src/focus-mixin.js';\nimport { TabindexMixin } from '@vaadin/a11y-base/src/tabindex-mixin.js';\n\n/**\n * A mixin providing common button functionality.\n *\n * @polymerMixin\n * @mixes ActiveMixin\n * @mixes FocusMixin\n * @mixes TabindexMixin\n */\nexport const ButtonMixin = (superClass) =>\n  class ButtonMixinClass extends ActiveMixin(TabindexMixin(FocusMixin(superClass))) {\n    static get properties() {\n      return {\n        /**\n         * Indicates whether the element can be focused and where it participates in sequential keyboard navigation.\n         *\n         * @override\n         * @protected\n         */\n        tabindex: {\n          type: Number,\n          value: 0,\n          reflectToAttribute: true,\n        },\n      };\n    }\n\n    /**\n     * By default, `Space` is the only possible activation key for a focusable HTML element.\n     * Nonetheless, the button is an exception as it can be also activated by pressing `Enter`.\n     * See the \"Keyboard Support\" section in https://www.w3.org/TR/wai-aria-practices/examples/button/button.html.\n     *\n     * @protected\n     * @override\n     */\n    get _activeKeys() {\n      return ['Enter', ' '];\n    }\n\n    /** @protected */\n    ready() {\n      super.ready();\n\n      // By default, if the user hasn't provided a custom role,\n      // the role attribute is set to \"button\".\n      if (!this.hasAttribute('role')) {\n        this.setAttribute('role', 'button');\n      }\n    }\n\n    /**\n     * Since the button component is designed on the base of the `[role=button]` attribute,\n     * and doesn't have a native <button> inside, in order to be fully accessible from the keyboard,\n     * it should manually fire the `click` event once an activation key is pressed,\n     * as it follows from the WAI-ARIA specifications:\n     * https://www.w3.org/TR/wai-aria-practices-1.1/#button\n     *\n     * According to the UI Events specifications,\n     * the `click` event should be fired exactly on `keydown`:\n     * https://www.w3.org/TR/uievents/#event-type-keydown\n     *\n     * @param {KeyboardEvent} event\n     * @protected\n     * @override\n     */\n    _onKeyDown(event) {\n      super._onKeyDown(event);\n\n      if (this._activeKeys.includes(event.key)) {\n        event.preventDefault();\n\n        // `DisabledMixin` overrides the standard `click()` method\n        // so that it doesn't fire the `click` event when the element is disabled.\n        this.click();\n      }\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';\nimport { ElementMixin } from '@vaadin/component-base/src/element-mixin.js';\nimport { TooltipController } from '@vaadin/component-base/src/tooltip-controller.js';\nimport { registerStyles, ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { buttonStyles, buttonTemplate } from './vaadin-button-base.js';\nimport { ButtonMixin } from './vaadin-button-mixin.js';\n\nregisterStyles('vaadin-button', buttonStyles, { moduleId: 'vaadin-button-styles' });\n\n/**\n * `<vaadin-button>` is an accessible and customizable button that allows users to perform actions.\n *\n * ```html\n * <vaadin-button>Press me</vaadin-button>\n * ```\n *\n * ### Styling\n *\n * The following shadow DOM parts are available for styling:\n *\n * Part name | Description\n * ----------|-------------\n * `label`   | The label (text) inside the button.\n * `prefix`  | A slot for content before the label (e.g. an icon).\n * `suffix`  | A slot for content after the label (e.g. an icon).\n *\n * The following attributes are available for styling:\n *\n * Attribute    | Description\n * -------------|-------------\n * `active`     | Set when the button is pressed down, either with mouse, touch or the keyboard.\n * `disabled`   | Set when the button is disabled.\n * `focus-ring` | Set when the button is focused using the keyboard.\n * `focused`    | Set when the button is focused.\n *\n * See [Styling Components](https://vaadin.com/docs/latest/styling/styling-components) documentation.\n *\n * @extends HTMLElement\n * @mixes ButtonMixin\n * @mixes ControllerMixin\n * @mixes ElementMixin\n * @mixes ThemableMixin\n */\nclass Button extends ButtonMixin(ElementMixin(ThemableMixin(ControllerMixin(PolymerElement)))) {\n  static get is() {\n    return 'vaadin-button';\n  }\n\n  static get template() {\n    return buttonTemplate(html);\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n\n    this._tooltipController = new TooltipController(this);\n    this.addController(this._tooltipController);\n  }\n}\n\ncustomElements.define(Button.is, Button);\n\nexport { Button };\n","import '@vaadin/vaadin-lumo-styles/color.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles(\n  'vaadin-date-picker-year',\n  css`\n    :host([current]) [part='year-number'] {\n      color: var(--lumo-primary-text-color);\n    }\n\n    :host(:not([current])) [part='year-number'],\n    [part='year-separator'] {\n      opacity: var(--_lumo-date-picker-year-opacity, 0.7);\n      transition: 0.2s opacity;\n    }\n\n    [part='year-number'],\n    [part='year-separator'] {\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      height: 50%;\n      transform: translateY(-50%);\n    }\n\n    [part='year-separator']::after {\n      color: var(--lumo-disabled-text-color);\n      content: '\\\\2022';\n    }\n  `,\n  { moduleId: 'lumo-date-picker-year' },\n);\n","import '@vaadin/vaadin-lumo-styles/color.js';\nimport '@vaadin/vaadin-lumo-styles/sizing.js';\nimport '@vaadin/vaadin-lumo-styles/spacing.js';\nimport '@vaadin/vaadin-lumo-styles/style.js';\nimport '@vaadin/vaadin-lumo-styles/typography.js';\nimport '@vaadin/button/theme/lumo/vaadin-button.js';\nimport './vaadin-date-picker-year-styles.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles(\n  'vaadin-date-picker-overlay-content',\n  css`\n    :host {\n      position: relative;\n      /* Background for the year scroller, placed here as we are using a mask image on the actual years part */\n      background-image: linear-gradient(var(--lumo-shade-5pct), var(--lumo-shade-5pct));\n      background-size: 57px 100%;\n      background-position: top right;\n      background-repeat: no-repeat;\n      cursor: default;\n    }\n\n    ::slotted([slot='months']) {\n      /* Month calendar height:\n              header height + margin-bottom\n            + weekdays height + margin-bottom\n            + date cell heights\n            + small margin between month calendars\n        */\n      /* prettier-ignore */\n      --vaadin-infinite-scroller-item-height:\n          calc(\n              var(--lumo-font-size-l) + var(--lumo-space-m)\n            + var(--lumo-font-size-xs) + var(--lumo-space-s)\n            + var(--lumo-size-m) * 6\n            + var(--lumo-space-s)\n          );\n      --vaadin-infinite-scroller-buffer-offset: 10%;\n      -webkit-mask-image: linear-gradient(transparent, #000 10%, #000 85%, transparent);\n      mask-image: linear-gradient(transparent, #000 10%, #000 85%, transparent);\n      position: relative;\n      margin-right: 57px;\n    }\n\n    ::slotted([slot='years']) {\n      /* TODO get rid of fixed magic number */\n      --vaadin-infinite-scroller-buffer-width: 97px;\n      width: 57px;\n      height: auto;\n      top: 0;\n      bottom: 0;\n      font-size: var(--lumo-font-size-s);\n      box-shadow: inset 2px 0 4px 0 var(--lumo-shade-5pct);\n      -webkit-mask-image: linear-gradient(transparent, #000 35%, #000 65%, transparent);\n      mask-image: linear-gradient(transparent, #000 35%, #000 65%, transparent);\n      cursor: var(--lumo-clickable-cursor);\n    }\n\n    ::slotted([slot='years']:hover) {\n      --_lumo-date-picker-year-opacity: 1;\n    }\n\n    /* TODO unsupported selector */\n    #scrollers {\n      position: static;\n      display: block;\n    }\n\n    /* TODO fix this in vaadin-date-picker that it adapts to the width of the year scroller */\n    :host([desktop]) ::slotted([slot='months']) {\n      right: auto;\n    }\n\n    /* Year scroller position indicator */\n    ::slotted([slot='years'])::before {\n      border: none;\n      width: 1em;\n      height: 1em;\n      background-color: var(--lumo-base-color);\n      background-image: linear-gradient(var(--lumo-tint-5pct), var(--lumo-tint-5pct));\n      transform: translate(-75%, -50%) rotate(45deg);\n      border-top-right-radius: var(--lumo-border-radius-s);\n      box-shadow: 2px -2px 6px 0 var(--lumo-shade-5pct);\n      z-index: 1;\n    }\n\n    [part='toolbar'] {\n      padding: var(--lumo-space-s);\n      border-bottom-left-radius: var(--lumo-border-radius-l);\n      margin-right: 57px;\n    }\n\n    [part='toolbar'] ::slotted(vaadin-button) {\n      margin: 0;\n    }\n\n    /* Narrow viewport mode (fullscreen) */\n\n    :host([fullscreen]) [part='toolbar'] {\n      order: -1;\n      background-color: var(--lumo-base-color);\n    }\n\n    :host([fullscreen]) [part='overlay-header'] {\n      order: -2;\n      height: var(--lumo-size-m);\n      padding: var(--lumo-space-s);\n      position: absolute;\n      left: 0;\n      right: 0;\n      justify-content: center;\n    }\n\n    :host([fullscreen]) [part='toggle-button'],\n    :host([fullscreen]) [part='clear-button'],\n    [part='overlay-header'] [part='label'] {\n      display: none;\n    }\n\n    /* Very narrow screen (year scroller initially hidden) */\n\n    [part='years-toggle-button'] {\n      display: flex;\n      align-items: center;\n      height: var(--lumo-size-s);\n      padding: 0 0.5em;\n      border-radius: var(--lumo-border-radius-m);\n      z-index: 3;\n      color: var(--lumo-primary-text-color);\n      font-weight: 500;\n      -webkit-font-smoothing: antialiased;\n      -moz-osx-font-smoothing: grayscale;\n    }\n\n    :host([years-visible]) [part='years-toggle-button'] {\n      background-color: var(--lumo-primary-color);\n      color: var(--lumo-primary-contrast-color);\n    }\n\n    /* TODO magic number (same as used for media-query in vaadin-date-picker-overlay-content) */\n    @media screen and (max-width: 374px) {\n      :host {\n        background-image: none;\n      }\n\n      [part='toolbar'],\n      ::slotted([slot='months']) {\n        margin-right: 0;\n      }\n\n      /* TODO make date-picker adapt to the width of the years part */\n      ::slotted([slot='years']) {\n        --vaadin-infinite-scroller-buffer-width: 90px;\n        width: 50px;\n        background-color: var(--lumo-shade-5pct);\n      }\n\n      :host([years-visible]) ::slotted([slot='months']) {\n        padding-left: 50px;\n      }\n    }\n  `,\n  { moduleId: 'lumo-date-picker-overlay-content' },\n);\n","import '@vaadin/vaadin-lumo-styles/color.js';\nimport '@vaadin/vaadin-lumo-styles/sizing.js';\nimport '@vaadin/vaadin-lumo-styles/spacing.js';\nimport '@vaadin/vaadin-lumo-styles/style.js';\nimport '@vaadin/vaadin-lumo-styles/typography.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles(\n  'vaadin-month-calendar',\n  css`\n    :host {\n      -moz-user-select: none;\n      -webkit-user-select: none;\n      -webkit-tap-highlight-color: transparent;\n      user-select: none;\n      font-size: var(--lumo-font-size-m);\n      color: var(--lumo-body-text-color);\n      text-align: center;\n      padding: 0 var(--lumo-space-xs);\n    }\n\n    /* Month header */\n\n    [part='month-header'] {\n      color: var(--lumo-header-text-color);\n      font-size: var(--lumo-font-size-l);\n      line-height: 1;\n      font-weight: 500;\n      margin-bottom: var(--lumo-space-m);\n    }\n\n    /* Week days and numbers */\n\n    [part='weekdays'],\n    [part='weekday'],\n    [part='week-number'] {\n      font-size: var(--lumo-font-size-xxs);\n      line-height: 1;\n      color: var(--lumo-secondary-text-color);\n    }\n\n    [part='weekdays'] {\n      margin-bottom: var(--lumo-space-s);\n    }\n\n    [part='weekday']:empty,\n    [part='week-number'] {\n      width: var(--lumo-size-xs);\n    }\n\n    /* Date and week number cells */\n\n    [part~='date'],\n    [part='week-number'] {\n      box-sizing: border-box;\n      display: inline-flex;\n      align-items: center;\n      justify-content: center;\n      height: var(--lumo-size-m);\n      position: relative;\n    }\n\n    [part~='date'] {\n      transition: color 0.1s;\n    }\n\n    [part~='date']:not(:empty) {\n      cursor: var(--lumo-clickable-cursor);\n    }\n\n    :host([week-numbers]) [part='weekday']:not(:empty),\n    :host([week-numbers]) [part~='date'] {\n      width: calc((100% - var(--lumo-size-xs)) / 7);\n    }\n\n    /* Today date */\n\n    [part~='date'][part~='today'] {\n      color: var(--lumo-primary-text-color);\n    }\n\n    /* Focused date */\n\n    [part~='date']::before {\n      content: '';\n      position: absolute;\n      z-index: -1;\n      top: 50%;\n      left: 50%;\n      transform: translate(-50%, -50%);\n      min-width: 2em;\n      min-height: 2em;\n      width: 80%;\n      height: 80%;\n      max-height: 100%;\n      max-width: 100%;\n      border-radius: var(--lumo-border-radius-m);\n    }\n\n    [part~='date'][part~='focused']::before {\n      box-shadow: 0 0 0 1px var(--lumo-base-color), 0 0 0 3px var(--lumo-primary-color-50pct);\n    }\n\n    :host(:not([focused])) [part~='date'][part~='focused']::before {\n      animation: vaadin-date-picker-month-calendar-focus-date 1.4s infinite;\n    }\n\n    @keyframes vaadin-date-picker-month-calendar-focus-date {\n      50% {\n        box-shadow: 0 0 0 1px var(--lumo-base-color), 0 0 0 3px transparent;\n      }\n    }\n\n    [part~='date']:not(:empty):not([part~='disabled']):not([part~='selected']):hover::before {\n      background-color: var(--lumo-primary-color-10pct);\n    }\n\n    [part~='date'][part~='selected'] {\n      color: var(--lumo-primary-contrast-color);\n    }\n\n    [part~='date'][part~='selected']::before {\n      background-color: var(--lumo-primary-color);\n    }\n\n    [part~='date'][part~='disabled'] {\n      color: var(--lumo-disabled-text-color);\n    }\n\n    @media (pointer: coarse) {\n      [part~='date']:hover:not([part~='selected'])::before,\n      [part~='focused']:not([part~='selected'])::before {\n        display: none;\n      }\n\n      [part~='date']:not(:empty):not([part~='disabled']):active::before {\n        display: block;\n      }\n\n      [part~='date'][part~='selected']::before {\n        box-shadow: none;\n      }\n    }\n\n    /* Disabled */\n\n    :host([disabled]) * {\n      color: var(--lumo-disabled-text-color) !important;\n    }\n  `,\n  { moduleId: 'lumo-month-calendar' },\n);\n\nconst template = document.createElement('template');\n\ntemplate.innerHTML = `\n  <style>\n    @keyframes vaadin-date-picker-month-calendar-focus-date {\n      50% {\n        box-shadow: 0 0 0 2px transparent;\n      }\n    }\n  </style>\n`;\n\ndocument.head.appendChild(template.content);\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport './version.js';\nimport { css } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { addLumoGlobalStyles } from './global.js';\n\nconst fontIcons = css`\n  @font-face {\n    font-family: 'lumo-icons';\n    src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABEgAAsAAAAAIjQAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAADsAAABUIIslek9TLzIAAAFEAAAAQwAAAFZAIUuKY21hcAAAAYgAAAD4AAADrsCU8d5nbHlmAAACgAAAC2cAABeAWri7U2hlYWQAAA3oAAAAMAAAADZa/6SsaGhlYQAADhgAAAAdAAAAJAbpA35obXR4AAAOOAAAABAAAACspBAAAGxvY2EAAA5IAAAAWAAAAFh57oA4bWF4cAAADqAAAAAfAAAAIAFKAXBuYW1lAAAOwAAAATEAAAIuUUJZCHBvc3QAAA/0AAABKwAA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T6pog6oOYKHtKakeakqKjHXpPwlGRcsC+OqxLIiJpXqoqqDMreG2l5bv9Ri3TRX+c23DZna9WFFgmXuO6Ps1Jm/w6ErW8N3FbHn/QC444j0AA==)\n      format('woff');\n    font-weight: normal;\n    font-style: normal;\n  }\n\n  html {\n    --lumo-icons-align-center: '\\\\ea01';\n    --lumo-icons-align-left: '\\\\ea02';\n    --lumo-icons-align-right: '\\\\ea03';\n    --lumo-icons-angle-down: '\\\\ea04';\n    --lumo-icons-angle-left: '\\\\ea05';\n    --lumo-icons-angle-right: '\\\\ea06';\n    --lumo-icons-angle-up: '\\\\ea07';\n    --lumo-icons-arrow-down: '\\\\ea08';\n    --lumo-icons-arrow-left: '\\\\ea09';\n    --lumo-icons-arrow-right: '\\\\ea0a';\n    --lumo-icons-arrow-up: '\\\\ea0b';\n    --lumo-icons-bar-chart: '\\\\ea0c';\n    --lumo-icons-bell: '\\\\ea0d';\n    --lumo-icons-calendar: '\\\\ea0e';\n    --lumo-icons-checkmark: '\\\\ea0f';\n    --lumo-icons-chevron-down: '\\\\ea10';\n    --lumo-icons-chevron-left: '\\\\ea11';\n    --lumo-icons-chevron-right: '\\\\ea12';\n    --lumo-icons-chevron-up: '\\\\ea13';\n    --lumo-icons-clock: '\\\\ea14';\n    --lumo-icons-cog: '\\\\ea15';\n    --lumo-icons-cross: '\\\\ea16';\n    --lumo-icons-download: '\\\\ea17';\n    --lumo-icons-dropdown: '\\\\ea18';\n    --lumo-icons-edit: '\\\\ea19';\n    --lumo-icons-error: '\\\\ea1a';\n    --lumo-icons-eye: '\\\\ea1b';\n    --lumo-icons-eye-disabled: '\\\\ea1c';\n    --lumo-icons-menu: '\\\\ea1d';\n    --lumo-icons-minus: '\\\\ea1e';\n    --lumo-icons-ordered-list: '\\\\ea1f';\n    --lumo-icons-phone: '\\\\ea20';\n    --lumo-icons-photo: '\\\\ea21';\n    --lumo-icons-play: '\\\\ea22';\n    --lumo-icons-plus: '\\\\ea23';\n    --lumo-icons-redo: '\\\\ea24';\n    --lumo-icons-reload: '\\\\ea25';\n    --lumo-icons-search: '\\\\ea26';\n    --lumo-icons-undo: '\\\\ea27';\n    --lumo-icons-unordered-list: '\\\\ea28';\n    --lumo-icons-upload: '\\\\ea29';\n    --lumo-icons-user: '\\\\ea2a';\n  }\n`;\n\naddLumoGlobalStyles('font-icons', fontIcons);\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '../color.js';\nimport '../font-icons.js';\nimport '../sizing.js';\nimport '../style.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst fieldButton = css`\n  [part$='button'] {\n    flex: none;\n    width: 1em;\n    height: 1em;\n    line-height: 1;\n    font-size: var(--lumo-icon-size-m);\n    text-align: center;\n    color: var(--lumo-contrast-60pct);\n    transition: 0.2s color;\n    cursor: var(--lumo-clickable-cursor);\n  }\n\n  [part$='button']:hover {\n    color: var(--lumo-contrast-90pct);\n  }\n\n  :host([disabled]) [part$='button'],\n  :host([readonly]) [part$='button'] {\n    color: var(--lumo-contrast-20pct);\n    cursor: default;\n  }\n\n  [part$='button']::before {\n    font-family: 'lumo-icons';\n    display: block;\n  }\n`;\nregisterStyles('', fieldButton, { moduleId: 'lumo-field-button' });\n\nexport { fieldButton };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '../color.js';\nimport '../sizing.js';\nimport '../style.js';\nimport '../typography.js';\nimport { css } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nexport const helper = css`\n  :host([has-helper]) [part='helper-text']::before {\n    content: '';\n    display: block;\n    height: 0.4em;\n  }\n\n  [part='helper-text'] {\n    display: block;\n    color: var(--lumo-secondary-text-color);\n    font-size: var(--lumo-font-size-xs);\n    line-height: var(--lumo-line-height-xs);\n    margin-left: calc(var(--lumo-border-radius-m) / 4);\n    transition: color 0.2s;\n  }\n\n  :host(:hover:not([readonly])) [part='helper-text'] {\n    color: var(--lumo-body-text-color);\n  }\n\n  :host([disabled]) [part='helper-text'] {\n    color: var(--lumo-disabled-text-color);\n    -webkit-text-fill-color: var(--lumo-disabled-text-color);\n  }\n\n  :host([has-helper][theme~='helper-above-field']) [part='helper-text']::before {\n    display: none;\n  }\n\n  :host([has-helper][theme~='helper-above-field']) [part='helper-text']::after {\n    content: '';\n    display: block;\n    height: 0.4em;\n  }\n\n  :host([has-helper][theme~='helper-above-field']) [part='label'] {\n    order: 0;\n    padding-bottom: 0.4em;\n  }\n\n  :host([has-helper][theme~='helper-above-field']) [part='helper-text'] {\n    order: 1;\n  }\n\n  :host([has-helper][theme~='helper-above-field']) [part='label'] + * {\n    order: 2;\n  }\n\n  :host([has-helper][theme~='helper-above-field']) [part='error-message'] {\n    order: 3;\n  }\n`;\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '../color.js';\nimport '../spacing.js';\nimport '../style.js';\nimport '../typography.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst requiredField = css`\n  [part='label'] {\n    align-self: flex-start;\n    color: var(--lumo-secondary-text-color);\n    font-weight: 500;\n    font-size: var(--lumo-font-size-s);\n    margin-left: calc(var(--lumo-border-radius-m) / 4);\n    transition: color 0.2s;\n    line-height: 1;\n    padding-right: 1em;\n    padding-bottom: 0.5em;\n    /* As a workaround for diacritics being cut off, add a top padding and a \n    negative margin to compensate */\n    padding-top: 0.25em;\n    margin-top: -0.25em;\n    overflow: hidden;\n    white-space: nowrap;\n    text-overflow: ellipsis;\n    position: relative;\n    max-width: 100%;\n    box-sizing: border-box;\n  }\n\n  :host([has-label])::before {\n    margin-top: calc(var(--lumo-font-size-s) * 1.5);\n  }\n\n  :host([has-label][theme~='small'])::before {\n    margin-top: calc(var(--lumo-font-size-xs) * 1.5);\n  }\n\n  :host([has-label]) {\n    padding-top: var(--lumo-space-m);\n  }\n\n  :host([has-label]) ::slotted([slot='tooltip']) {\n    --vaadin-tooltip-offset-bottom: calc((var(--lumo-space-m) - var(--lumo-space-xs)) * -1);\n  }\n\n  :host([required]) [part='required-indicator']::after {\n    content: var(--lumo-required-field-indicator, '\\\\2022');\n    transition: opacity 0.2s;\n    color: var(--lumo-required-field-indicator-color, var(--lumo-primary-text-color));\n    position: absolute;\n    right: 0;\n    width: 1em;\n    text-align: center;\n  }\n\n  :host([invalid]) [part='required-indicator']::after {\n    color: var(--lumo-required-field-indicator-color, var(--lumo-error-text-color));\n  }\n\n  [part='error-message'] {\n    margin-left: calc(var(--lumo-border-radius-m) / 4);\n    font-size: var(--lumo-font-size-xs);\n    line-height: var(--lumo-line-height-xs);\n    color: var(--lumo-error-text-color);\n    will-change: max-height;\n    transition: 0.4s max-height;\n    max-height: 5em;\n  }\n\n  :host([has-error-message]) [part='error-message']::before,\n  :host([has-error-message]) [part='error-message']::after {\n    content: '';\n    display: block;\n    height: 0.4em;\n  }\n\n  :host(:not([invalid])) [part='error-message'] {\n    max-height: 0;\n    overflow: hidden;\n  }\n\n  /* RTL specific styles */\n\n  :host([dir='rtl']) [part='label'] {\n    margin-left: 0;\n    margin-right: calc(var(--lumo-border-radius-m) / 4);\n  }\n\n  :host([dir='rtl']) [part='label'] {\n    padding-left: 1em;\n    padding-right: 0;\n  }\n\n  :host([dir='rtl']) [part='required-indicator']::after {\n    right: auto;\n    left: 0;\n  }\n\n  :host([dir='rtl']) [part='error-message'] {\n    margin-left: 0;\n    margin-right: calc(var(--lumo-border-radius-m) / 4);\n  }\n`;\n\nregisterStyles('', requiredField, { moduleId: 'lumo-required-field' });\n\nexport { requiredField };\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '../color.js';\nimport '../font-icons.js';\nimport '../sizing.js';\nimport '../spacing.js';\nimport '../style.js';\nimport '../typography.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { fieldButton } from './field-button.js';\nimport { helper } from './helper.js';\nimport { requiredField } from './required-field.js';\n\nconst inputField = css`\n  :host {\n    --lumo-text-field-size: var(--lumo-size-m);\n    color: var(--lumo-body-text-color);\n    font-size: var(--lumo-font-size-m);\n    font-family: var(--lumo-font-family);\n    -webkit-font-smoothing: antialiased;\n    -moz-osx-font-smoothing: grayscale;\n    -webkit-tap-highlight-color: transparent;\n    padding: var(--lumo-space-xs) 0;\n  }\n\n  :host::before {\n    height: var(--lumo-text-field-size);\n    box-sizing: border-box;\n    display: inline-flex;\n    align-items: center;\n  }\n\n  :host([focused]:not([readonly])) [part='label'] {\n    color: var(--lumo-primary-text-color);\n  }\n\n  :host([focused]) [part='input-field'] ::slotted(:is(input, textarea)) {\n    -webkit-mask-image: none;\n    mask-image: none;\n  }\n\n  ::slotted(:is(input, textarea):placeholder-shown) {\n    color: var(--lumo-secondary-text-color);\n  }\n\n  /* Hover */\n  :host(:hover:not([readonly]):not([focused])) [part='label'] {\n    color: var(--lumo-body-text-color);\n  }\n\n  :host(:hover:not([readonly]):not([focused])) [part='input-field']::after {\n    opacity: 0.1;\n  }\n\n  /* Touch device adjustment */\n  @media (pointer: coarse) {\n    :host(:hover:not([readonly]):not([focused])) [part='label'] {\n      color: var(--lumo-secondary-text-color);\n    }\n\n    :host(:hover:not([readonly]):not([focused])) [part='input-field']::after {\n      opacity: 0;\n    }\n\n    :host(:active:not([readonly]):not([focused])) [part='input-field']::after {\n      opacity: 0.2;\n    }\n  }\n\n  /* Trigger when not focusing using the keyboard */\n  :host([focused]:not([focus-ring]):not([readonly])) [part='input-field']::after {\n    transform: scaleX(0);\n    transition-duration: 0.15s, 1s;\n  }\n\n  /* Focus-ring */\n  :host([focus-ring]) [part='input-field'] {\n    box-shadow: 0 0 0 2px var(--lumo-primary-color-50pct);\n  }\n\n  /* Read-only and disabled */\n  :host(:is([readonly], [disabled])) ::slotted(:is(input, textarea):placeholder-shown) {\n    opacity: 0;\n  }\n\n  /* Read-only style */\n  :host([readonly]) {\n    --vaadin-input-field-border-color: transparent;\n  }\n\n  /* Disabled style */\n  :host([disabled]) {\n    pointer-events: none;\n    --vaadin-input-field-border-color: var(--lumo-contrast-20pct);\n  }\n\n  :host([disabled]) [part='label'],\n  :host([disabled]) [part='input-field'] ::slotted(*) {\n    color: var(--lumo-disabled-text-color);\n    -webkit-text-fill-color: var(--lumo-disabled-text-color);\n  }\n\n  /* Invalid style */\n  :host([invalid]) {\n    --vaadin-input-field-border-color: var(--lumo-error-color);\n  }\n\n  :host([invalid][focus-ring]) [part='input-field'] {\n    box-shadow: 0 0 0 2px var(--lumo-error-color-50pct);\n  }\n\n  :host([input-prevented]) [part='input-field'] {\n    animation: shake 0.15s infinite;\n  }\n\n  @keyframes shake {\n    25% {\n      transform: translateX(4px);\n    }\n    75% {\n      transform: translateX(-4px);\n    }\n  }\n\n  /* Small theme */\n  :host([theme~='small']) {\n    font-size: var(--lumo-font-size-s);\n    --lumo-text-field-size: var(--lumo-size-s);\n  }\n\n  :host([theme~='small']) [part='label'] {\n    font-size: var(--lumo-font-size-xs);\n  }\n\n  :host([theme~='small']) [part='error-message'] {\n    font-size: var(--lumo-font-size-xxs);\n  }\n\n  /* Slotted content */\n  [part='input-field'] ::slotted(:not(vaadin-icon):not(input):not(textarea)) {\n    color: var(--lumo-secondary-text-color);\n    font-weight: 400;\n  }\n\n  [part='clear-button']::before {\n    content: var(--lumo-icons-cross);\n  }\n`;\n\nconst inputFieldShared = [requiredField, fieldButton, helper, inputField];\n\nregisterStyles('', inputFieldShared, {\n  moduleId: 'lumo-input-field-shared-styles',\n});\n\nexport { inputField, inputFieldShared };\n","import '@vaadin/vaadin-lumo-styles/font-icons.js';\nimport { inputFieldShared } from '@vaadin/vaadin-lumo-styles/mixins/input-field-shared.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst datePicker = css`\n  :host {\n    outline: none;\n  }\n\n  [part='toggle-button']::before {\n    content: var(--lumo-icons-calendar);\n  }\n\n  [part='clear-button']::before {\n    content: var(--lumo-icons-cross);\n  }\n\n  @media (max-width: 420px), (max-height: 420px) {\n    [part='overlay-content'] {\n      height: 70vh;\n    }\n  }\n\n  :host([dir='rtl']) [part='input-field'] ::slotted(input) {\n    --_lumo-text-field-overflow-mask-image: linear-gradient(to left, transparent, #000 1.25em);\n  }\n\n  :host([dir='rtl']) [part='input-field'] ::slotted(input:placeholder-shown) {\n    --_lumo-text-field-overflow-mask-image: none;\n  }\n`;\n\nregisterStyles('vaadin-date-picker', [inputFieldShared, datePicker], { moduleId: 'lumo-date-picker' });\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { getAncestorRootNodes } from '@vaadin/component-base/src/dom-utils.js';\n\nconst PROP_NAMES_VERTICAL = {\n  start: 'top',\n  end: 'bottom',\n};\n\nconst PROP_NAMES_HORIZONTAL = {\n  start: 'left',\n  end: 'right',\n};\n\nconst targetResizeObserver = new ResizeObserver((entries) => {\n  setTimeout(() => {\n    entries.forEach((entry) => {\n      if (entry.target.__overlay) {\n        entry.target.__overlay._updatePosition();\n      }\n    });\n  });\n});\n\n/**\n * @polymerMixin\n */\nexport const PositionMixin = (superClass) =>\n  class PositionMixin extends superClass {\n    static get properties() {\n      return {\n        /**\n         * The element next to which this overlay should be aligned.\n         * The position of the overlay relative to the positionTarget can be adjusted\n         * with properties `horizontalAlign`, `verticalAlign`, `noHorizontalOverlap`\n         * and `noVerticalOverlap`.\n         */\n        positionTarget: {\n          type: Object,\n          value: null,\n        },\n\n        /**\n         * When `positionTarget` is set, this property defines whether to align the overlay's\n         * left or right side to the target element by default.\n         * Possible values are `start` and `end`.\n         * RTL is taken into account when interpreting the value.\n         * The overlay is automatically flipped to the opposite side when it doesn't fit into\n         * the default side defined by this property.\n         *\n         * @attr {start|end} horizontal-align\n         */\n        horizontalAlign: {\n          type: String,\n          value: 'start',\n        },\n\n        /**\n         * When `positionTarget` is set, this property defines whether to align the overlay's\n         * top or bottom side to the target element by default.\n         * Possible values are `top` and `bottom`.\n         * The overlay is automatically flipped to the opposite side when it doesn't fit into\n         * the default side defined by this property.\n         *\n         * @attr {top|bottom} vertical-align\n         */\n        verticalAlign: {\n          type: String,\n          value: 'top',\n        },\n\n        /**\n         * When `positionTarget` is set, this property defines whether the overlay should overlap\n         * the target element in the x-axis, or be positioned right next to it.\n         *\n         * @attr {boolean} no-horizontal-overlap\n         */\n        noHorizontalOverlap: {\n          type: Boolean,\n          value: false,\n        },\n\n        /**\n         * When `positionTarget` is set, this property defines whether the overlay should overlap\n         * the target element in the y-axis, or be positioned right above/below it.\n         *\n         * @attr {boolean} no-vertical-overlap\n         */\n        noVerticalOverlap: {\n          type: Boolean,\n          value: false,\n        },\n\n        /**\n         * If the overlay content has no intrinsic height, this property can be used to set\n         * the minimum vertical space (in pixels) required by the overlay. Setting a value to\n         * the property effectively disables the content measurement in favor of using this\n         * fixed value for determining the open direction.\n         *\n         * @attr {number} required-vertical-space\n         */\n        requiredVerticalSpace: {\n          type: Number,\n          value: 0,\n        },\n      };\n    }\n\n    static get observers() {\n      return [\n        '__positionSettingsChanged(horizontalAlign, verticalAlign, noHorizontalOverlap, noVerticalOverlap, requiredVerticalSpace)',\n        '__overlayOpenedChanged(opened, positionTarget)',\n      ];\n    }\n\n    constructor() {\n      super();\n\n      this.__onScroll = this.__onScroll.bind(this);\n      this._updatePosition = this._updatePosition.bind(this);\n    }\n\n    /** @protected */\n    connectedCallback() {\n      super.connectedCallback();\n\n      if (this.opened) {\n        this.__addUpdatePositionEventListeners();\n      }\n    }\n\n    /** @protected */\n    disconnectedCallback() {\n      super.disconnectedCallback();\n      this.__removeUpdatePositionEventListeners();\n    }\n\n    /** @private */\n    __addUpdatePositionEventListeners() {\n      window.addEventListener('resize', this._updatePosition);\n\n      this.__positionTargetAncestorRootNodes = getAncestorRootNodes(this.positionTarget);\n      this.__positionTargetAncestorRootNodes.forEach((node) => {\n        node.addEventListener('scroll', this.__onScroll, true);\n      });\n    }\n\n    /** @private */\n    __removeUpdatePositionEventListeners() {\n      window.removeEventListener('resize', this._updatePosition);\n\n      if (this.__positionTargetAncestorRootNodes) {\n        this.__positionTargetAncestorRootNodes.forEach((node) => {\n          node.removeEventListener('scroll', this.__onScroll, true);\n        });\n        this.__positionTargetAncestorRootNodes = null;\n      }\n    }\n\n    /** @private */\n    __overlayOpenedChanged(opened, positionTarget) {\n      this.__removeUpdatePositionEventListeners();\n\n      if (positionTarget) {\n        positionTarget.__overlay = null;\n        targetResizeObserver.unobserve(positionTarget);\n\n        if (opened) {\n          this.__addUpdatePositionEventListeners();\n          positionTarget.__overlay = this;\n          targetResizeObserver.observe(positionTarget);\n        }\n      }\n\n      if (opened) {\n        const computedStyle = getComputedStyle(this);\n        if (!this.__margins) {\n          this.__margins = {};\n          ['top', 'bottom', 'left', 'right'].forEach((propName) => {\n            this.__margins[propName] = parseInt(computedStyle[propName], 10);\n          });\n        }\n        this.setAttribute('dir', computedStyle.direction);\n\n        this._updatePosition();\n        // Schedule another position update (to cover virtual keyboard opening for example)\n        requestAnimationFrame(() => this._updatePosition());\n      }\n    }\n\n    __positionSettingsChanged() {\n      this._updatePosition();\n    }\n\n    /** @private */\n    __onScroll(e) {\n      // If the scroll event occurred inside the overlay, ignore it.\n      if (!this.contains(e.target)) {\n        this._updatePosition();\n      }\n    }\n\n    _updatePosition() {\n      if (!this.positionTarget || !this.opened) {\n        return;\n      }\n\n      const targetRect = this.positionTarget.getBoundingClientRect();\n\n      // Detect the desired alignment and update the layout accordingly\n      const shouldAlignStartVertically = this.__shouldAlignStartVertically(targetRect);\n      this.style.justifyContent = shouldAlignStartVertically ? 'flex-start' : 'flex-end';\n\n      const isRTL = this.__isRTL;\n      const shouldAlignStartHorizontally = this.__shouldAlignStartHorizontally(targetRect, isRTL);\n      const flexStart = (!isRTL && shouldAlignStartHorizontally) || (isRTL && !shouldAlignStartHorizontally);\n      this.style.alignItems = flexStart ? 'flex-start' : 'flex-end';\n\n      // Get the overlay rect after possible overlay alignment changes\n      const overlayRect = this.getBoundingClientRect();\n\n      // Obtain vertical positioning properties\n      const verticalProps = this.__calculatePositionInOneDimension(\n        targetRect,\n        overlayRect,\n        this.noVerticalOverlap,\n        PROP_NAMES_VERTICAL,\n        this,\n        shouldAlignStartVertically,\n      );\n\n      // Obtain horizontal positioning properties\n      const horizontalProps = this.__calculatePositionInOneDimension(\n        targetRect,\n        overlayRect,\n        this.noHorizontalOverlap,\n        PROP_NAMES_HORIZONTAL,\n        this,\n        shouldAlignStartHorizontally,\n      );\n\n      // Apply the positioning properties to the overlay\n      Object.assign(this.style, verticalProps, horizontalProps);\n\n      this.toggleAttribute('bottom-aligned', !shouldAlignStartVertically);\n      this.toggleAttribute('top-aligned', shouldAlignStartVertically);\n\n      this.toggleAttribute('end-aligned', !flexStart);\n      this.toggleAttribute('start-aligned', flexStart);\n    }\n\n    __shouldAlignStartHorizontally(targetRect, rtl) {\n      // Using previous size to fix a case where window resize may cause the overlay to be squeezed\n      // smaller than its current space before the fit-calculations.\n      const contentWidth = Math.max(this.__oldContentWidth || 0, this.$.overlay.offsetWidth);\n      this.__oldContentWidth = this.$.overlay.offsetWidth;\n\n      const viewportWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);\n      const defaultAlignLeft = (!rtl && this.horizontalAlign === 'start') || (rtl && this.horizontalAlign === 'end');\n\n      return this.__shouldAlignStart(\n        targetRect,\n        contentWidth,\n        viewportWidth,\n        this.__margins,\n        defaultAlignLeft,\n        this.noHorizontalOverlap,\n        PROP_NAMES_HORIZONTAL,\n      );\n    }\n\n    __shouldAlignStartVertically(targetRect) {\n      // Using previous size to fix a case where window resize may cause the overlay to be squeezed\n      // smaller than its current space before the fit-calculations.\n      const contentHeight =\n        this.requiredVerticalSpace || Math.max(this.__oldContentHeight || 0, this.$.overlay.offsetHeight);\n      this.__oldContentHeight = this.$.overlay.offsetHeight;\n\n      const viewportHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);\n      const defaultAlignTop = this.verticalAlign === 'top';\n\n      return this.__shouldAlignStart(\n        targetRect,\n        contentHeight,\n        viewportHeight,\n        this.__margins,\n        defaultAlignTop,\n        this.noVerticalOverlap,\n        PROP_NAMES_VERTICAL,\n      );\n    }\n\n    // eslint-disable-next-line max-params\n    __shouldAlignStart(targetRect, contentSize, viewportSize, margins, defaultAlignStart, noOverlap, propNames) {\n      const spaceForStartAlignment =\n        viewportSize - targetRect[noOverlap ? propNames.end : propNames.start] - margins[propNames.end];\n      const spaceForEndAlignment = targetRect[noOverlap ? propNames.start : propNames.end] - margins[propNames.start];\n\n      const spaceForDefaultAlignment = defaultAlignStart ? spaceForStartAlignment : spaceForEndAlignment;\n      const spaceForOtherAlignment = defaultAlignStart ? spaceForEndAlignment : spaceForStartAlignment;\n\n      const shouldGoToDefaultSide =\n        spaceForDefaultAlignment > spaceForOtherAlignment || spaceForDefaultAlignment > contentSize;\n\n      return defaultAlignStart === shouldGoToDefaultSide;\n    }\n\n    /**\n     * Returns an adjusted value after resizing the browser window,\n     * to avoid wrong calculations when e.g. previously set `bottom`\n     * CSS property value is larger than the updated viewport height.\n     * See https://github.com/vaadin/web-components/issues/4604\n     */\n    __adjustBottomProperty(cssPropNameToSet, propNames, currentValue) {\n      let adjustedProp;\n\n      if (cssPropNameToSet === propNames.end) {\n        // Adjust horizontally\n        if (propNames.end === PROP_NAMES_VERTICAL.end) {\n          const viewportHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);\n\n          if (currentValue > viewportHeight && this.__oldViewportHeight) {\n            const heightDiff = this.__oldViewportHeight - viewportHeight;\n            adjustedProp = currentValue - heightDiff;\n          }\n\n          this.__oldViewportHeight = viewportHeight;\n        }\n\n        // Adjust vertically\n        if (propNames.end === PROP_NAMES_HORIZONTAL.end) {\n          const viewportWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);\n\n          if (currentValue > viewportWidth && this.__oldViewportWidth) {\n            const widthDiff = this.__oldViewportWidth - viewportWidth;\n            adjustedProp = currentValue - widthDiff;\n          }\n\n          this.__oldViewportWidth = viewportWidth;\n        }\n      }\n\n      return adjustedProp;\n    }\n\n    /**\n     * Returns an object with CSS position properties to set,\n     * e.g. { top: \"100px\" }\n     */\n    // eslint-disable-next-line max-params\n    __calculatePositionInOneDimension(targetRect, overlayRect, noOverlap, propNames, overlay, shouldAlignStart) {\n      const cssPropNameToSet = shouldAlignStart ? propNames.start : propNames.end;\n      const cssPropNameToClear = shouldAlignStart ? propNames.end : propNames.start;\n\n      const currentValue = parseFloat(overlay.style[cssPropNameToSet] || getComputedStyle(overlay)[cssPropNameToSet]);\n      const adjustedValue = this.__adjustBottomProperty(cssPropNameToSet, propNames, currentValue);\n\n      const diff =\n        overlayRect[shouldAlignStart ? propNames.start : propNames.end] -\n        targetRect[noOverlap === shouldAlignStart ? propNames.end : propNames.start];\n\n      const valueToSet = adjustedValue\n        ? `${adjustedValue}px`\n        : `${currentValue + diff * (shouldAlignStart ? -1 : 1)}px`;\n\n      return {\n        [cssPropNameToSet]: valueToSet,\n        [cssPropNameToClear]: '',\n      };\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { Overlay } from '@vaadin/overlay/src/vaadin-overlay.js';\nimport { PositionMixin } from '@vaadin/overlay/src/vaadin-overlay-position-mixin.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles(\n  'vaadin-date-picker-overlay',\n  css`\n    [part='overlay'] {\n      display: flex;\n      flex: auto;\n    }\n\n    [part~='content'] {\n      flex: auto;\n    }\n\n    @media (forced-colors: active) {\n      [part='overlay'] {\n        outline: 3px solid;\n      }\n    }\n  `,\n  {\n    moduleId: 'vaadin-date-picker-overlay-styles',\n  },\n);\n\nlet memoizedTemplate;\n\n/**\n * An element used internally by `<vaadin-date-picker>`. Not intended to be used separately.\n *\n * @extends Overlay\n * @private\n */\nclass DatePickerOverlay extends PositionMixin(Overlay) {\n  static get is() {\n    return 'vaadin-date-picker-overlay';\n  }\n\n  static get template() {\n    if (!memoizedTemplate) {\n      memoizedTemplate = super.template.cloneNode(true);\n      memoizedTemplate.content.querySelector('[part~=\"overlay\"]').removeAttribute('tabindex');\n    }\n\n    return memoizedTemplate;\n  }\n}\n\ncustomElements.define(DatePickerOverlay.is, DatePickerOverlay);\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport { dedupingMixin } from '../utils/mixin.js';\n\n// Common implementation for mixin & behavior\nfunction mutablePropertyChange(inst, property, value, old, mutableData) {\n  let isObject;\n  if (mutableData) {\n    isObject = (typeof value === 'object' && value !== null);\n    // Pull `old` for Objects from temp cache, but treat `null` as a primitive\n    if (isObject) {\n      old = inst.__dataTemp[property];\n    }\n  }\n  // Strict equality check, but return false for NaN===NaN\n  let shouldChange = (old !== value && (old === old || value === value));\n  // Objects are stored in temporary cache (cleared at end of\n  // turn), which is used for dirty-checking\n  if (isObject && shouldChange) {\n    inst.__dataTemp[property] = value;\n  }\n  return shouldChange;\n}\n\n/**\n * Element class mixin to skip strict dirty-checking for objects and arrays\n * (always consider them to be \"dirty\"), for use on elements utilizing\n * `PropertyEffects`\n *\n * By default, `PropertyEffects` performs strict dirty checking on\n * objects, which means that any deep modifications to an object or array will\n * not be propagated unless \"immutable\" data patterns are used (i.e. all object\n * references from the root to the mutation were changed).\n *\n * Polymer also provides a proprietary data mutation and path notification API\n * (e.g. `notifyPath`, `set`, and array mutation API's) that allow efficient\n * mutation and notification of deep changes in an object graph to all elements\n * bound to the same object graph.\n *\n * In cases where neither immutable patterns nor the data mutation API can be\n * used, applying this mixin will cause Polymer to skip dirty checking for\n * objects and arrays (always consider them to be \"dirty\").  This allows a\n * user to make a deep modification to a bound object graph, and then either\n * simply re-set the object (e.g. `this.items = this.items`) or call `notifyPath`\n * (e.g. `this.notifyPath('items')`) to update the tree.  Note that all\n * elements that wish to be updated based on deep mutations must apply this\n * mixin or otherwise skip strict dirty checking for objects/arrays.\n * Specifically, any elements in the binding tree between the source of a\n * mutation and the consumption of it must apply this mixin or enable the\n * `OptionalMutableData` mixin.\n *\n * In order to make the dirty check strategy configurable, see\n * `OptionalMutableData`.\n *\n * Note, the performance characteristics of propagating large object graphs\n * will be worse as opposed to using strict dirty checking with immutable\n * patterns or Polymer's path notification API.\n *\n * @mixinFunction\n * @polymer\n * @summary Element class mixin to skip strict dirty-checking for objects\n *   and arrays\n * @template T\n * @param {function(new:T)} superClass Class to apply mixin to.\n * @return {function(new:T)} superClass with mixin applied.\n */\nexport const MutableData = dedupingMixin(superClass => {\n\n  /**\n   * @polymer\n   * @mixinClass\n   * @implements {Polymer_MutableData}\n   */\n  class MutableData extends superClass {\n    /**\n     * Overrides `PropertyEffects` to provide option for skipping\n     * strict equality checking for Objects and Arrays.\n     *\n     * This method pulls the value to dirty check against from the `__dataTemp`\n     * cache (rather than the normal `__data` cache) for Objects.  Since the temp\n     * cache is cleared at the end of a turn, this implementation allows\n     * side-effects of deep object changes to be processed by re-setting the\n     * same object (using the temp cache as an in-turn backstop to prevent\n     * cycles due to 2-way notification).\n     *\n     * @param {string} property Property name\n     * @param {*} value New property value\n     * @param {*} old Previous property value\n     * @return {boolean} Whether the property should be considered a change\n     * @protected\n     */\n    _shouldPropertyChange(property, value, old) {\n      return mutablePropertyChange(this, property, value, old, true);\n    }\n\n  }\n\n  return MutableData;\n\n});\n\n/**\n * Element class mixin to add the optional ability to skip strict\n * dirty-checking for objects and arrays (always consider them to be\n * \"dirty\") by setting a `mutable-data` attribute on an element instance.\n *\n * By default, `PropertyEffects` performs strict dirty checking on\n * objects, which means that any deep modifications to an object or array will\n * not be propagated unless \"immutable\" data patterns are used (i.e. all object\n * references from the root to the mutation were changed).\n *\n * Polymer also provides a proprietary data mutation and path notification API\n * (e.g. `notifyPath`, `set`, and array mutation API's) that allow efficient\n * mutation and notification of deep changes in an object graph to all elements\n * bound to the same object graph.\n *\n * In cases where neither immutable patterns nor the data mutation API can be\n * used, applying this mixin will allow Polymer to skip dirty checking for\n * objects and arrays (always consider them to be \"dirty\").  This allows a\n * user to make a deep modification to a bound object graph, and then either\n * simply re-set the object (e.g. `this.items = this.items`) or call `notifyPath`\n * (e.g. `this.notifyPath('items')`) to update the tree.  Note that all\n * elements that wish to be updated based on deep mutations must apply this\n * mixin or otherwise skip strict dirty checking for objects/arrays.\n * Specifically, any elements in the binding tree between the source of a\n * mutation and the consumption of it must enable this mixin or apply the\n * `MutableData` mixin.\n *\n * While this mixin adds the ability to forgo Object/Array dirty checking,\n * the `mutableData` flag defaults to false and must be set on the instance.\n *\n * Note, the performance characteristics of propagating large object graphs\n * will be worse by relying on `mutableData: true` as opposed to using\n * strict dirty checking with immutable patterns or Polymer's path notification\n * API.\n *\n * @mixinFunction\n * @polymer\n * @summary Element class mixin to optionally skip strict dirty-checking\n *   for objects and arrays\n */\nexport const OptionalMutableData = dedupingMixin(superClass => {\n\n  /**\n   * @mixinClass\n   * @polymer\n   * @implements {Polymer_OptionalMutableData}\n   */\n  class OptionalMutableData extends superClass {\n\n    /** @nocollapse */\n    static get properties() {\n      return {\n        /**\n         * Instance-level flag for configuring the dirty-checking strategy\n         * for this element.  When true, Objects and Arrays will skip dirty\n         * checking, otherwise strict equality checking will be used.\n         */\n        mutableData: Boolean\n      };\n    }\n\n    /**\n     * Overrides `PropertyEffects` to provide option for skipping\n     * strict equality checking for Objects and Arrays.\n     *\n     * When `this.mutableData` is true on this instance, this method\n     * pulls the value to dirty check against from the `__dataTemp` cache\n     * (rather than the normal `__data` cache) for Objects.  Since the temp\n     * cache is cleared at the end of a turn, this implementation allows\n     * side-effects of deep object changes to be processed by re-setting the\n     * same object (using the temp cache as an in-turn backstop to prevent\n     * cycles due to 2-way notification).\n     *\n     * @param {string} property Property name\n     * @param {*} value New property value\n     * @param {*} old Previous property value\n     * @return {boolean} Whether the property should be considered a change\n     * @protected\n     */\n    _shouldPropertyChange(property, value, old) {\n      return mutablePropertyChange(this, property, value, old, this.mutableData);\n    }\n  }\n\n  return OptionalMutableData;\n\n});\n\n// Export for use by legacy behavior\nMutableData._mutablePropertyChange = mutablePropertyChange;\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\n/**\n * Module for preparing and stamping instances of templates that utilize\n * Polymer's data-binding and declarative event listener features.\n *\n * Example:\n *\n *     // Get a template from somewhere, e.g. light DOM\n *     let template = this.querySelector('template');\n *     // Prepare the template\n *     let TemplateClass = Templatize.templatize(template);\n *     // Instance the template with an initial data model\n *     let instance = new TemplateClass({myProp: 'initial'});\n *     // Insert the instance's DOM somewhere, e.g. element's shadow DOM\n *     this.shadowRoot.appendChild(instance.root);\n *     // Changing a property on the instance will propagate to bindings\n *     // in the template\n *     instance.myProp = 'new value';\n *\n * The `options` dictionary passed to `templatize` allows for customizing\n * features of the generated template class, including how outer-scope host\n * properties should be forwarded into template instances, how any instance\n * properties added into the template's scope should be notified out to\n * the host, and whether the instance should be decorated as a \"parent model\"\n * of any event handlers.\n *\n *     // Customize property forwarding and event model decoration\n *     let TemplateClass = Templatize.templatize(template, this, {\n *       parentModel: true,\n *       forwardHostProp(property, value) {...},\n *       instanceProps: {...},\n *       notifyInstanceProp(instance, property, value) {...},\n *     });\n *\n * @summary Module for preparing and stamping instances of templates\n *   utilizing Polymer templating features.\n */\n\nimport './boot.js';\n\nimport { PropertyEffects } from '../mixins/property-effects.js';\nimport { MutableData } from '../mixins/mutable-data.js';\nimport { strictTemplatePolicy, legacyWarnings } from './settings.js';\nimport { wrap } from './wrap.js';\n\n// Base class for HTMLTemplateElement extension that has property effects\n// machinery for propagating host properties to children. This is an ES5\n// class only because Babel (incorrectly) requires super() in the class\n// constructor even though no `this` is used and it returns an instance.\nlet newInstance = null;\n\n/**\n * @constructor\n * @extends {HTMLTemplateElement}\n * @private\n */\nfunction HTMLTemplateElementExtension() { return newInstance; }\nHTMLTemplateElementExtension.prototype = Object.create(HTMLTemplateElement.prototype, {\n  constructor: {\n    value: HTMLTemplateElementExtension,\n    writable: true\n  }\n});\n\n/**\n * @constructor\n * @implements {Polymer_PropertyEffects}\n * @extends {HTMLTemplateElementExtension}\n * @private\n */\nconst DataTemplate = PropertyEffects(HTMLTemplateElementExtension);\n\n/**\n * @constructor\n * @implements {Polymer_MutableData}\n * @extends {DataTemplate}\n * @private\n */\nconst MutableDataTemplate = MutableData(DataTemplate);\n\n// Applies a DataTemplate subclass to a <template> instance\nfunction upgradeTemplate(template, constructor) {\n  newInstance = template;\n  Object.setPrototypeOf(template, constructor.prototype);\n  new constructor();\n  newInstance = null;\n}\n\n/**\n * Base class for TemplateInstance.\n * @constructor\n * @extends {HTMLElement}\n * @implements {Polymer_PropertyEffects}\n * @private\n */\nconst templateInstanceBase = PropertyEffects(class {});\n\nexport function showHideChildren(hide, children) {\n  for (let i=0; i<children.length; i++) {\n    let n = children[i];\n    // Ignore non-changes\n    if (Boolean(hide) != Boolean(n.__hideTemplateChildren__)) {\n      // clear and restore text\n      if (n.nodeType === Node.TEXT_NODE) {\n        if (hide) {\n          n.__polymerTextContent__ = n.textContent;\n          n.textContent = '';\n        } else {\n          n.textContent = n.__polymerTextContent__;\n        }\n      // remove and replace slot\n      } else if (n.localName === 'slot') {\n        if (hide) {\n          n.__polymerReplaced__ = document.createComment('hidden-slot');\n          wrap(wrap(n).parentNode).replaceChild(n.__polymerReplaced__, n);\n        } else {\n          const replace = n.__polymerReplaced__;\n          if (replace) {\n            wrap(wrap(replace).parentNode).replaceChild(n, replace);\n          }\n        }\n      }\n      // hide and show nodes\n      else if (n.style) {\n        if (hide) {\n          n.__polymerDisplay__ = n.style.display;\n          n.style.display = 'none';\n        } else {\n          n.style.display = n.__polymerDisplay__;\n        }\n      }\n    }\n    n.__hideTemplateChildren__ = hide;\n    if (n._showHideChildren) {\n      n._showHideChildren(hide);\n    }\n  }\n}\n\n/**\n * @polymer\n * @customElement\n * @appliesMixin PropertyEffects\n * @unrestricted\n */\nclass TemplateInstanceBase extends templateInstanceBase {\n  constructor(props) {\n    super();\n    this._configureProperties(props);\n    /** @type {!StampedTemplate} */\n    this.root = this._stampTemplate(this.__dataHost);\n    // Save list of stamped children\n    let children = [];\n    /** @suppress {invalidCasts} */\n    this.children = /** @type {!NodeList} */ (children);\n    // Polymer 1.x did not use `Polymer.dom` here so not bothering.\n    for (let n = this.root.firstChild; n; n=n.nextSibling) {\n      children.push(n);\n      n.__templatizeInstance = this;\n    }\n    if (this.__templatizeOwner &&\n      this.__templatizeOwner.__hideTemplateChildren__) {\n      this._showHideChildren(true);\n    }\n    // Flush props only when props are passed if instance props exist\n    // or when there isn't instance props.\n    let options = this.__templatizeOptions;\n    if ((props && options.instanceProps) || !options.instanceProps) {\n      this._enableProperties();\n    }\n  }\n  /**\n   * Configure the given `props` by calling `_setPendingProperty`. Also\n   * sets any properties stored in `__hostProps`.\n   * @private\n   * @param {Object} props Object of property name-value pairs to set.\n   * @return {void}\n   */\n  _configureProperties(props) {\n    let options = this.__templatizeOptions;\n    if (options.forwardHostProp) {\n      for (let hprop in this.__hostProps) {\n        this._setPendingProperty(hprop, this.__dataHost['_host_' + hprop]);\n      }\n    }\n    // Any instance props passed in the constructor will overwrite host props;\n    // normally this would be a user error but we don't specifically filter them\n    for (let iprop in props) {\n      this._setPendingProperty(iprop, props[iprop]);\n    }\n  }\n  /**\n   * Forwards a host property to this instance.  This method should be\n   * called on instances from the `options.forwardHostProp` callback\n   * to propagate changes of host properties to each instance.\n   *\n   * Note this method enqueues the change, which are flushed as a batch.\n   *\n   * @param {string} prop Property or path name\n   * @param {*} value Value of the property to forward\n   * @return {void}\n   */\n  forwardHostProp(prop, value) {\n    if (this._setPendingPropertyOrPath(prop, value, false, true)) {\n      this.__dataHost._enqueueClient(this);\n    }\n  }\n\n  /**\n   * Override point for adding custom or simulated event handling.\n   *\n   * @override\n   * @param {!Node} node Node to add event listener to\n   * @param {string} eventName Name of event\n   * @param {function(!Event):void} handler Listener function to add\n   * @return {void}\n   */\n  _addEventListenerToNode(node, eventName, handler) {\n    if (this._methodHost && this.__templatizeOptions.parentModel) {\n      // If this instance should be considered a parent model, decorate\n      // events this template instance as `model`\n      this._methodHost._addEventListenerToNode(node, eventName, (e) => {\n        e.model = this;\n        handler(e);\n      });\n    } else {\n      // Otherwise delegate to the template's host (which could be)\n      // another template instance\n      let templateHost = this.__dataHost.__dataHost;\n      if (templateHost) {\n        templateHost._addEventListenerToNode(node, eventName, handler);\n      }\n    }\n  }\n  /**\n   * Shows or hides the template instance top level child elements. For\n   * text nodes, `textContent` is removed while \"hidden\" and replaced when\n   * \"shown.\"\n   * @param {boolean} hide Set to true to hide the children;\n   * set to false to show them.\n   * @return {void}\n   * @protected\n   */\n  _showHideChildren(hide) {\n    showHideChildren(hide, this.children);\n  }\n  /**\n   * Overrides default property-effects implementation to intercept\n   * textContent bindings while children are \"hidden\" and cache in\n   * private storage for later retrieval.\n   *\n   * @override\n   * @param {!Node} node The node to set a property on\n   * @param {string} prop The property to set\n   * @param {*} value The value to set\n   * @return {void}\n   * @protected\n   */\n  _setUnmanagedPropertyToNode(node, prop, value) {\n    if (node.__hideTemplateChildren__ &&\n        node.nodeType == Node.TEXT_NODE && prop == 'textContent') {\n      node.__polymerTextContent__ = value;\n    } else {\n      super._setUnmanagedPropertyToNode(node, prop, value);\n    }\n  }\n  /**\n   * Find the parent model of this template instance.  The parent model\n   * is either another templatize instance that had option `parentModel: true`,\n   * or else the host element.\n   *\n   * @return {!Polymer_PropertyEffects} The parent model of this instance\n   */\n  get parentModel() {\n    let model = this.__parentModel;\n    if (!model) {\n      let options;\n      model = this;\n      do {\n        // A template instance's `__dataHost` is a <template>\n        // `model.__dataHost.__dataHost` is the template's host\n        model = model.__dataHost.__dataHost;\n      } while ((options = model.__templatizeOptions) && !options.parentModel);\n      this.__parentModel = model;\n    }\n    return model;\n  }\n\n  /**\n   * Stub of HTMLElement's `dispatchEvent`, so that effects that may\n   * dispatch events safely no-op.\n   *\n   * @param {Event} event Event to dispatch\n   * @return {boolean} Always true.\n   * @override\n   */\n   dispatchEvent(event) { // eslint-disable-line no-unused-vars\n     return true;\n  }\n}\n\n/** @type {!DataTemplate} */\nTemplateInstanceBase.prototype.__dataHost;\n/** @type {!TemplatizeOptions} */\nTemplateInstanceBase.prototype.__templatizeOptions;\n/** @type {!Polymer_PropertyEffects} */\nTemplateInstanceBase.prototype._methodHost;\n/** @type {!Object} */\nTemplateInstanceBase.prototype.__templatizeOwner;\n/** @type {!Object} */\nTemplateInstanceBase.prototype.__hostProps;\n\n/**\n * @constructor\n * @extends {TemplateInstanceBase}\n * @implements {Polymer_MutableData}\n * @private\n */\nconst MutableTemplateInstanceBase = MutableData(\n    // This cast shouldn't be neccessary, but Closure doesn't understand that\n    // TemplateInstanceBase is a constructor function.\n    /** @type {function(new:TemplateInstanceBase)} */ (TemplateInstanceBase));\n\nfunction findMethodHost(template) {\n  // Technically this should be the owner of the outermost template.\n  // In shadow dom, this is always getRootNode().host, but we can\n  // approximate this via cooperation with our dataHost always setting\n  // `_methodHost` as long as there were bindings (or id's) on this\n  // instance causing it to get a dataHost.\n  let templateHost = template.__dataHost;\n  return templateHost && templateHost._methodHost || templateHost;\n}\n\n/* eslint-disable valid-jsdoc */\n/**\n * @suppress {missingProperties} class.prototype is not defined for some reason\n */\nfunction createTemplatizerClass(template, templateInfo, options) {\n  /**\n   * @constructor\n   * @extends {TemplateInstanceBase}\n   */\n  let templatizerBase = options.mutableData ?\n    MutableTemplateInstanceBase : TemplateInstanceBase;\n\n  // Affordance for global mixins onto TemplatizeInstance\n  if (templatize.mixin) {\n    templatizerBase = templatize.mixin(templatizerBase);\n  }\n\n  /**\n   * Anonymous class created by the templatize\n   * @constructor\n   * @private\n   */\n  let klass = class extends templatizerBase { };\n  /** @override */\n  klass.prototype.__templatizeOptions = options;\n  klass.prototype._bindTemplate(template);\n  addNotifyEffects(klass, template, templateInfo, options);\n  return klass;\n}\n\n/**\n * Adds propagate effects from the template to the template instance for\n * properties that the host binds to the template using the `_host_` prefix.\n *\n * @suppress {missingProperties} class.prototype is not defined for some reason\n */\nfunction addPropagateEffects(target, templateInfo, options, methodHost) {\n  let userForwardHostProp = options.forwardHostProp;\n  if (userForwardHostProp && templateInfo.hasHostProps) {\n    // Under the `removeNestedTemplates` optimization, a custom element like\n    // `dom-if` or `dom-repeat` can itself be treated as the \"template\"; this\n    // flag is used to switch between upgrading a `<template>` to be a property\n    // effects client vs. adding the effects directly to the custom element\n    const isTemplate = target.localName == 'template';\n    // Provide data API and property effects on memoized template class\n    let klass = templateInfo.templatizeTemplateClass;\n    if (!klass) {\n      if (isTemplate) {\n        /**\n         * @constructor\n         * @extends {DataTemplate}\n         */\n        let templatizedBase =\n            options.mutableData ? MutableDataTemplate : DataTemplate;\n\n        // NOTE: due to https://github.com/google/closure-compiler/issues/2928,\n        // combining the next two lines into one assignment causes a spurious\n        // type error.\n        /** @private */\n        class TemplatizedTemplate extends templatizedBase {}\n        klass = templateInfo.templatizeTemplateClass = TemplatizedTemplate;\n      } else {\n        /**\n         * @constructor\n         * @extends {PolymerElement}\n         */\n        const templatizedBase = target.constructor;\n\n        // Create a cached subclass of the base custom element class onto which\n        // to put the template-specific propagate effects\n        // NOTE: due to https://github.com/google/closure-compiler/issues/2928,\n        // combining the next two lines into one assignment causes a spurious\n        // type error.\n        /** @private */\n        class TemplatizedTemplateExtension extends templatizedBase {}\n        klass = templateInfo.templatizeTemplateClass =\n            TemplatizedTemplateExtension;\n      }\n      // Add template - >instances effects\n      // and host <- template effects\n      let hostProps = templateInfo.hostProps;\n      for (let prop in hostProps) {\n        klass.prototype._addPropertyEffect('_host_' + prop,\n          klass.prototype.PROPERTY_EFFECT_TYPES.PROPAGATE,\n          {fn: createForwardHostPropEffect(prop, userForwardHostProp)});\n        klass.prototype._createNotifyingProperty('_host_' + prop);\n      }\n      if (legacyWarnings && methodHost) {\n        warnOnUndeclaredProperties(templateInfo, options, methodHost);\n      }\n    }\n    // Mix any pre-bound data into __data; no need to flush this to\n    // instances since they pull from the template at instance-time\n    if (target.__dataProto) {\n      // Note, generally `__dataProto` could be chained, but it's guaranteed\n      // to not be since this is a vanilla template we just added effects to\n      Object.assign(target.__data, target.__dataProto);\n    }\n    if (isTemplate) {\n      upgradeTemplate(target, klass);\n      // Clear any pending data for performance\n      target.__dataTemp = {};\n      target.__dataPending = null;\n      target.__dataOld = null;\n      target._enableProperties();\n    } else {\n      // Swizzle the cached subclass prototype onto the custom element\n      Object.setPrototypeOf(target, klass.prototype);\n      // Check for any pre-bound instance host properties, and do the\n      // instance property delete/assign dance for those (directly into data;\n      // not need to go through accessor since they are pulled at instance time)\n      const hostProps = templateInfo.hostProps;\n      for (let prop in hostProps) {\n        prop = '_host_' + prop;\n        if (prop in target) {\n          const val = target[prop];\n          delete target[prop];\n          target.__data[prop] = val;\n        }\n      }\n    }\n  }\n}\n/* eslint-enable valid-jsdoc */\n\nfunction createForwardHostPropEffect(hostProp, userForwardHostProp) {\n  return function forwardHostProp(template, prop, props) {\n    userForwardHostProp.call(template.__templatizeOwner,\n      prop.substring('_host_'.length), props[prop]);\n  };\n}\n\nfunction addNotifyEffects(klass, template, templateInfo, options) {\n  let hostProps = templateInfo.hostProps || {};\n  for (let iprop in options.instanceProps) {\n    delete hostProps[iprop];\n    let userNotifyInstanceProp = options.notifyInstanceProp;\n    if (userNotifyInstanceProp) {\n      klass.prototype._addPropertyEffect(iprop,\n        klass.prototype.PROPERTY_EFFECT_TYPES.NOTIFY,\n        {fn: createNotifyInstancePropEffect(iprop, userNotifyInstanceProp)});\n    }\n  }\n  if (options.forwardHostProp && template.__dataHost) {\n    for (let hprop in hostProps) {\n      // As we're iterating hostProps in this function, note whether\n      // there were any, for an optimization in addPropagateEffects\n      if (!templateInfo.hasHostProps) {\n        templateInfo.hasHostProps = true;\n      }\n      klass.prototype._addPropertyEffect(hprop,\n        klass.prototype.PROPERTY_EFFECT_TYPES.NOTIFY,\n        {fn: createNotifyHostPropEffect()});\n    }\n  }\n}\n\nfunction createNotifyInstancePropEffect(instProp, userNotifyInstanceProp) {\n  return function notifyInstanceProp(inst, prop, props) {\n    userNotifyInstanceProp.call(inst.__templatizeOwner,\n      inst, prop, props[prop]);\n  };\n}\n\nfunction createNotifyHostPropEffect() {\n  return function notifyHostProp(inst, prop, props) {\n    inst.__dataHost._setPendingPropertyOrPath('_host_' + prop, props[prop], true, true);\n  };\n}\n\n\n/**\n * Returns an anonymous `PropertyEffects` class bound to the\n * `<template>` provided.  Instancing the class will result in the\n * template being stamped into a document fragment stored as the instance's\n * `root` property, after which it can be appended to the DOM.\n *\n * Templates may utilize all Polymer data-binding features as well as\n * declarative event listeners.  Event listeners and inline computing\n * functions in the template will be called on the host of the template.\n *\n * The constructor returned takes a single argument dictionary of initial\n * property values to propagate into template bindings.  Additionally\n * host properties can be forwarded in, and instance properties can be\n * notified out by providing optional callbacks in the `options` dictionary.\n *\n * Valid configuration in `options` are as follows:\n *\n * - `forwardHostProp(property, value)`: Called when a property referenced\n *   in the template changed on the template's host. As this library does\n *   not retain references to templates instanced by the user, it is the\n *   templatize owner's responsibility to forward host property changes into\n *   user-stamped instances.  The `instance.forwardHostProp(property, value)`\n *    method on the generated class should be called to forward host\n *   properties into the template to prevent unnecessary property-changed\n *   notifications. Any properties referenced in the template that are not\n *   defined in `instanceProps` will be notified up to the template's host\n *   automatically.\n * - `instanceProps`: Dictionary of property names that will be added\n *   to the instance by the templatize owner.  These properties shadow any\n *   host properties, and changes within the template to these properties\n *   will result in `notifyInstanceProp` being called.\n * - `mutableData`: When `true`, the generated class will skip strict\n *   dirty-checking for objects and arrays (always consider them to be\n *   \"dirty\").\n * - `notifyInstanceProp(instance, property, value)`: Called when\n *   an instance property changes.  Users may choose to call `notifyPath`\n *   on e.g. the owner to notify the change.\n * - `parentModel`: When `true`, events handled by declarative event listeners\n *   (`on-event=\"handler\"`) will be decorated with a `model` property pointing\n *   to the template instance that stamped it.  It will also be returned\n *   from `instance.parentModel` in cases where template instance nesting\n *   causes an inner model to shadow an outer model.\n *\n * All callbacks are called bound to the `owner`. Any context\n * needed for the callbacks (such as references to `instances` stamped)\n * should be stored on the `owner` such that they can be retrieved via\n * `this`.\n *\n * When `options.forwardHostProp` is declared as an option, any properties\n * referenced in the template will be automatically forwarded from the host of\n * the `<template>` to instances, with the exception of any properties listed in\n * the `options.instanceProps` object.  `instanceProps` are assumed to be\n * managed by the owner of the instances, either passed into the constructor\n * or set after the fact.  Note, any properties passed into the constructor will\n * always be set to the instance (regardless of whether they would normally\n * be forwarded from the host).\n *\n * Note that `templatize()` can be run only once for a given `<template>`.\n * Further calls will result in an error. Also, there is a special\n * behavior if the template was duplicated through a mechanism such as\n * `<dom-repeat>` or `<test-fixture>`. In this case, all calls to\n * `templatize()` return the same class for all duplicates of a template.\n * The class returned from `templatize()` is generated only once using\n * the `options` from the first call. This means that any `options`\n * provided to subsequent calls will be ignored. Therefore, it is very\n * important not to close over any variables inside the callbacks. Also,\n * arrow functions must be avoided because they bind the outer `this`.\n * Inside the callbacks, any contextual information can be accessed\n * through `this`, which points to the `owner`.\n *\n * @param {!HTMLTemplateElement} template Template to templatize\n * @param {Polymer_PropertyEffects=} owner Owner of the template instances;\n *   any optional callbacks will be bound to this owner.\n * @param {Object=} options Options dictionary (see summary for details)\n * @return {function(new:TemplateInstanceBase, Object=)} Generated class bound\n *   to the template provided\n * @suppress {invalidCasts}\n */\nexport function templatize(template, owner, options) {\n  // Under strictTemplatePolicy, the templatized element must be owned\n  // by a (trusted) Polymer element, indicated by existence of _methodHost;\n  // e.g. for dom-if & dom-repeat in main document, _methodHost is null\n  if (strictTemplatePolicy && !findMethodHost(template)) {\n    throw new Error('strictTemplatePolicy: template owner not trusted');\n  }\n  options = /** @type {!TemplatizeOptions} */(options || {});\n  if (template.__templatizeOwner) {\n    throw new Error('A <template> can only be templatized once');\n  }\n  template.__templatizeOwner = owner;\n  const ctor = owner ? owner.constructor : TemplateInstanceBase;\n  let templateInfo = ctor._parseTemplate(template);\n  // Get memoized base class for the prototypical template, which\n  // includes property effects for binding template & forwarding\n  /**\n   * @constructor\n   * @extends {TemplateInstanceBase}\n   */\n  let baseClass = templateInfo.templatizeInstanceClass;\n  if (!baseClass) {\n    baseClass = createTemplatizerClass(template, templateInfo, options);\n    templateInfo.templatizeInstanceClass = baseClass;\n  }\n  const methodHost = findMethodHost(template);\n  // Host property forwarding must be installed onto template instance\n  addPropagateEffects(template, templateInfo, options, methodHost);\n  // Subclass base class and add reference for this specific template\n  /** @private */\n  let klass = class TemplateInstance extends baseClass {};\n  /** @override */\n  klass.prototype._methodHost = methodHost;\n  /** @override */\n  klass.prototype.__dataHost = /** @type {!DataTemplate} */ (template);\n  /** @override */\n  klass.prototype.__templatizeOwner = /** @type {!Object} */ (owner);\n  /** @override */\n  klass.prototype.__hostProps = templateInfo.hostProps;\n  klass = /** @type {function(new:TemplateInstanceBase)} */(klass); //eslint-disable-line no-self-assign\n  return klass;\n}\n\nfunction warnOnUndeclaredProperties(templateInfo, options, methodHost) {\n  const declaredProps = methodHost.constructor._properties;\n  const {propertyEffects} = templateInfo;\n  const {instanceProps} = options;\n  for (let prop in propertyEffects) {\n    // Ensure properties with template effects are declared on the outermost\n    // host (`methodHost`), unless they are instance props or static functions\n    if (!declaredProps[prop] && !(instanceProps && instanceProps[prop])) {\n      const effects = propertyEffects[prop];\n      for (let i=0; i<effects.length; i++) {\n        const {part} = effects[i].info;\n        if (!(part.signature && part.signature.static)) {\n          console.warn(`Property '${prop}' used in template but not ` +\n            `declared in 'properties'; attribute will not be observed.`);\n          break;\n        }\n      }\n    }\n  }\n}\n\n/**\n * Returns the template \"model\" associated with a given element, which\n * serves as the binding scope for the template instance the element is\n * contained in. A template model is an instance of\n * `TemplateInstanceBase`, and should be used to manipulate data\n * associated with this template instance.\n *\n * Example:\n *\n *   let model = modelForElement(el);\n *   if (model.index < 10) {\n *     model.set('item.checked', true);\n *   }\n *\n * @param {HTMLElement} template The model will be returned for\n *   elements stamped from this template (accepts either an HTMLTemplateElement)\n *   or a `<dom-if>`/`<dom-repeat>` element when using `removeNestedTemplates`\n *   optimization.\n * @param {Node=} node Node for which to return a template model.\n * @return {TemplateInstanceBase} Template instance representing the\n *   binding scope for the element\n */\nexport function modelForElement(template, node) {\n  let model;\n  while (node) {\n    // An element with a __templatizeInstance marks the top boundary\n    // of a scope; walk up until we find one, and then ensure that\n    // its __dataHost matches `this`, meaning this dom-repeat stamped it\n    if ((model = node.__dataHost ? node : node.__templatizeInstance)) {\n      // Found an element stamped by another template; keep walking up\n      // from its __dataHost\n      if (model.__dataHost != template) {\n        node = model.__dataHost;\n      } else {\n        return model;\n      }\n    } else {\n      // Still in a template scope, keep going up until\n      // a __templatizeInstance is found\n      node = wrap(node).parentNode;\n    }\n  }\n  return null;\n}\n\nexport { TemplateInstanceBase };\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\n\nimport './mixin.js';\nimport './async.js';\n\n/**\n * @summary Collapse multiple callbacks into one invocation after a timer.\n */\nexport class Debouncer {\n  constructor() {\n    this._asyncModule = null;\n    this._callback = null;\n    this._timer = null;\n  }\n  /**\n   * Sets the scheduler; that is, a module with the Async interface,\n   * a callback and optional arguments to be passed to the run function\n   * from the async module.\n   *\n   * @param {!AsyncInterface} asyncModule Object with Async interface.\n   * @param {function()} callback Callback to run.\n   * @return {void}\n   */\n  setConfig(asyncModule, callback) {\n    this._asyncModule = asyncModule;\n    this._callback = callback;\n    this._timer = this._asyncModule.run(() => {\n      this._timer = null;\n      debouncerQueue.delete(this);\n      this._callback();\n    });\n  }\n  /**\n   * Cancels an active debouncer and returns a reference to itself.\n   *\n   * @return {void}\n   */\n  cancel() {\n    if (this.isActive()) {\n      this._cancelAsync();\n      // Canceling a debouncer removes its spot from the flush queue,\n      // so if a debouncer is manually canceled and re-debounced, it\n      // will reset its flush order (this is a very minor difference from 1.x)\n      // Re-debouncing via the `debounce` API retains the 1.x FIFO flush order\n      debouncerQueue.delete(this);\n    }\n  }\n  /**\n   * Cancels a debouncer's async callback.\n   *\n   * @return {void}\n   */\n  _cancelAsync() {\n    if (this.isActive()) {\n      this._asyncModule.cancel(/** @type {number} */(this._timer));\n      this._timer = null;\n    }\n  }\n  /**\n   * Flushes an active debouncer and returns a reference to itself.\n   *\n   * @return {void}\n   */\n  flush() {\n    if (this.isActive()) {\n      this.cancel();\n      this._callback();\n    }\n  }\n  /**\n   * Returns true if the debouncer is active.\n   *\n   * @return {boolean} True if active.\n   */\n  isActive() {\n    return this._timer != null;\n  }\n  /**\n   * Creates a debouncer if no debouncer is passed as a parameter\n   * or it cancels an active debouncer otherwise. The following\n   * example shows how a debouncer can be called multiple times within a\n   * microtask and \"debounced\" such that the provided callback function is\n   * called once. Add this method to a custom element:\n   *\n   * ```js\n   * import {microTask} from '@polymer/polymer/lib/utils/async.js';\n   * import {Debouncer} from '@polymer/polymer/lib/utils/debounce.js';\n   * // ...\n   *\n   * _debounceWork() {\n   *   this._debounceJob = Debouncer.debounce(this._debounceJob,\n   *       microTask, () => this._doWork());\n   * }\n   * ```\n   *\n   * If the `_debounceWork` method is called multiple times within the same\n   * microtask, the `_doWork` function will be called only once at the next\n   * microtask checkpoint.\n   *\n   * Note: In testing it is often convenient to avoid asynchrony. To accomplish\n   * this with a debouncer, you can use `enqueueDebouncer` and\n   * `flush`. For example, extend the above example by adding\n   * `enqueueDebouncer(this._debounceJob)` at the end of the\n   * `_debounceWork` method. Then in a test, call `flush` to ensure\n   * the debouncer has completed.\n   *\n   * @param {Debouncer?} debouncer Debouncer object.\n   * @param {!AsyncInterface} asyncModule Object with Async interface\n   * @param {function()} callback Callback to run.\n   * @return {!Debouncer} Returns a debouncer object.\n   */\n  static debounce(debouncer, asyncModule, callback) {\n    if (debouncer instanceof Debouncer) {\n      // Cancel the async callback, but leave in debouncerQueue if it was\n      // enqueued, to maintain 1.x flush order\n      debouncer._cancelAsync();\n    } else {\n      debouncer = new Debouncer();\n    }\n    debouncer.setConfig(asyncModule, callback);\n    return debouncer;\n  }\n}\n\nlet debouncerQueue = new Set();\n\n/**\n * Adds a `Debouncer` to a list of globally flushable tasks.\n *\n * @param {!Debouncer} debouncer Debouncer to enqueue\n * @return {void}\n */\nexport const enqueueDebouncer = function(debouncer) {\n  debouncerQueue.add(debouncer);\n};\n\n/**\n * Flushes any enqueued debouncers\n *\n * @return {boolean} Returns whether any debouncers were flushed\n */\nexport const flushDebouncers = function() {\n  const didFlush = Boolean(debouncerQueue.size);\n  // If new debouncers are added while flushing, Set.forEach will ensure\n  // newly added ones are also flushed\n  debouncerQueue.forEach(debouncer => {\n    try {\n      debouncer.flush();\n    } catch(e) {\n      setTimeout(() => {\n        throw e;\n      });\n    }\n  });\n  return didFlush;\n};","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport './boot.js';\nimport {enqueueDebouncer, flushDebouncers} from '../utils/debounce.js';\nexport {enqueueDebouncer};\n\n/**\n * Forces several classes of asynchronously queued tasks to flush:\n * - Debouncers added via `enqueueDebouncer`\n * - ShadyDOM distribution\n *\n * @return {void}\n */\nexport const flush = function() {\n  let shadyDOM, debouncers;\n  do {\n    shadyDOM = window.ShadyDOM && ShadyDOM.flush();\n    if (window.ShadyCSS && window.ShadyCSS.ScopingShim) {\n      window.ShadyCSS.ScopingShim.flush();\n    }\n    debouncers = flushDebouncers();\n  } while (shadyDOM || debouncers);\n};\n","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\n\n/**\n * @fileoverview\n *\n * Module to hide `<dom-bind>`, `<dom-if>`, and `<dom-repeat>` elements\n * optimally in ShadyDOM\n */\n\nimport {legacyOptimizations, useShadow} from './settings.js';\n\nlet elementsHidden = false;\n\n/**\n * @return {boolean} True if elements will be hidden globally\n */\nexport function hideElementsGlobally() {\n  if (legacyOptimizations && !useShadow) {\n    if (!elementsHidden) {\n      elementsHidden = true;\n      const style = document.createElement('style');\n      style.textContent = 'dom-bind,dom-if,dom-repeat{display:none;}';\n      document.head.appendChild(style);\n    }\n    return true;\n  }\n  return false;\n}","/**\n@license\nCopyright (c) 2017 The Polymer Project Authors. All rights reserved.\nThis code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\nThe complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\nThe complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\nCode distributed by Google as part of the polymer project is also\nsubject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n*/\nimport { PolymerElement } from '../../polymer-element.js';\n\nimport { TemplateInstanceBase, templatize, modelForElement } from '../utils/templatize.js'; // eslint-disable-line no-unused-vars\nimport { Debouncer } from '../utils/debounce.js';\nimport { enqueueDebouncer, flush } from '../utils/flush.js';\nimport { OptionalMutableData } from '../mixins/mutable-data.js';\nimport { matches, translate } from '../utils/path.js';\nimport { timeOut, microTask } from '../utils/async.js';\nimport { wrap } from '../utils/wrap.js';\nimport { hideElementsGlobally } from '../utils/hide-template-controls.js';\nimport { suppressTemplateNotifications } from '../utils/settings.js';\n\n/**\n * @constructor\n * @implements {Polymer_OptionalMutableData}\n * @extends {PolymerElement}\n * @private\n */\nconst domRepeatBase = OptionalMutableData(PolymerElement);\n\n/**\n * The `<dom-repeat>` element will automatically stamp and binds one instance\n * of template content to each object in a user-provided array.\n * `dom-repeat` accepts an `items` property, and one instance of the template\n * is stamped for each item into the DOM at the location of the `dom-repeat`\n * element.  The `item` property will be set on each instance's binding\n * scope, thus templates should bind to sub-properties of `item`.\n *\n * Example:\n *\n * ```html\n * <dom-module id=\"employee-list\">\n *\n *   <template>\n *\n *     <div> Employee list: </div>\n *     <dom-repeat items=\"{{employees}}\">\n *       <template>\n *         <div>First name: <span>{{item.first}}</span></div>\n *         <div>Last name: <span>{{item.last}}</span></div>\n *       </template>\n *     </dom-repeat>\n *\n *   </template>\n *\n * </dom-module>\n * ```\n *\n * With the following custom element definition:\n *\n * ```js\n * class EmployeeList extends PolymerElement {\n *   static get is() { return 'employee-list'; }\n *   static get properties() {\n *     return {\n *       employees: {\n *         value() {\n *           return [\n *             {first: 'Bob', last: 'Smith'},\n *             {first: 'Sally', last: 'Johnson'},\n *             ...\n *           ];\n *         }\n *       }\n *     };\n *   }\n * }\n * ```\n *\n * Notifications for changes to items sub-properties will be forwarded to template\n * instances, which will update via the normal structured data notification system.\n *\n * Mutations to the `items` array itself should be made using the Array\n * mutation API's on the PropertyEffects mixin (`push`, `pop`, `splice`,\n * `shift`, `unshift`), and template instances will be kept in sync with the\n * data in the array.\n *\n * Events caught by event handlers within the `dom-repeat` template will be\n * decorated with a `model` property, which represents the binding scope for\n * each template instance.  The model should be used to manipulate data on the\n * instance, for example `event.model.set('item.checked', true);`.\n *\n * Alternatively, the model for a template instance for an element stamped by\n * a `dom-repeat` can be obtained using the `modelForElement` API on the\n * `dom-repeat` that stamped it, for example\n * `this.$.domRepeat.modelForElement(event.target).set('item.checked', true);`.\n * This may be useful for manipulating instance data of event targets obtained\n * by event handlers on parents of the `dom-repeat` (event delegation).\n *\n * A view-specific filter/sort may be applied to each `dom-repeat` by supplying a\n * `filter` and/or `sort` property.  This may be a string that names a function on\n * the host, or a function may be assigned to the property directly.  The functions\n * should implemented following the standard `Array` filter/sort API.\n *\n * In order to re-run the filter or sort functions based on changes to sub-fields\n * of `items`, the `observe` property may be set as a space-separated list of\n * `item` sub-fields that should cause a re-filter/sort when modified.  If\n * the filter or sort function depends on properties not contained in `items`,\n * the user should observe changes to those properties and call `render` to update\n * the view based on the dependency change.\n *\n * For example, for an `dom-repeat` with a filter of the following:\n *\n * ```js\n * isEngineer(item) {\n *   return item.type == 'engineer' || item.manager.type == 'engineer';\n * }\n * ```\n *\n * Then the `observe` property should be configured as follows:\n *\n * ```html\n * <dom-repeat items=\"{{employees}}\" filter=\"isEngineer\" observe=\"type manager.type\">\n * ```\n *\n * @customElement\n * @polymer\n * @extends {domRepeatBase}\n * @appliesMixin OptionalMutableData\n * @summary Custom element for stamping instance of a template bound to\n *   items in an array.\n */\nexport class DomRepeat extends domRepeatBase {\n\n  // Not needed to find template; can be removed once the analyzer\n  // can find the tag name from customElements.define call\n  static get is() { return 'dom-repeat'; }\n\n  static get template() { return null; }\n\n  static get properties() {\n\n    /**\n     * Fired whenever DOM is added or removed by this template (by\n     * default, rendering occurs lazily).  To force immediate rendering, call\n     * `render`.\n     *\n     * @event dom-change\n     */\n    return {\n\n      /**\n       * An array containing items determining how many instances of the template\n       * to stamp and that that each template instance should bind to.\n       */\n      items: {\n        type: Array\n      },\n\n      /**\n       * The name of the variable to add to the binding scope for the array\n       * element associated with a given template instance.\n       */\n      as: {\n        type: String,\n        value: 'item'\n      },\n\n      /**\n       * The name of the variable to add to the binding scope with the index\n       * of the instance in the sorted and filtered list of rendered items.\n       * Note, for the index in the `this.items` array, use the value of the\n       * `itemsIndexAs` property.\n       */\n      indexAs: {\n        type: String,\n        value: 'index'\n      },\n\n      /**\n       * The name of the variable to add to the binding scope with the index\n       * of the instance in the `this.items` array. Note, for the index of\n       * this instance in the sorted and filtered list of rendered items,\n       * use the value of the `indexAs` property.\n       */\n      itemsIndexAs: {\n        type: String,\n        value: 'itemsIndex'\n      },\n\n      /**\n       * A function that should determine the sort order of the items.  This\n       * property should either be provided as a string, indicating a method\n       * name on the element's host, or else be an actual function.  The\n       * function should match the sort function passed to `Array.sort`.\n       * Using a sort function has no effect on the underlying `items` array.\n       */\n      sort: {\n        type: Function,\n        observer: '__sortChanged'\n      },\n\n      /**\n       * A function that can be used to filter items out of the view.  This\n       * property should either be provided as a string, indicating a method\n       * name on the element's host, or else be an actual function.  The\n       * function should match the sort function passed to `Array.filter`.\n       * Using a filter function has no effect on the underlying `items` array.\n       */\n      filter: {\n        type: Function,\n        observer: '__filterChanged'\n      },\n\n      /**\n       * When using a `filter` or `sort` function, the `observe` property\n       * should be set to a space-separated list of the names of item\n       * sub-fields that should trigger a re-sort or re-filter when changed.\n       * These should generally be fields of `item` that the sort or filter\n       * function depends on.\n       */\n      observe: {\n        type: String,\n        observer: '__observeChanged'\n      },\n\n      /**\n       * When using a `filter` or `sort` function, the `delay` property\n       * determines a debounce time in ms after a change to observed item\n       * properties that must pass before the filter or sort is re-run.\n       * This is useful in rate-limiting shuffling of the view when\n       * item changes may be frequent.\n       */\n      delay: Number,\n\n      /**\n       * Count of currently rendered items after `filter` (if any) has been applied.\n       * If \"chunking mode\" is enabled, `renderedItemCount` is updated each time a\n       * set of template instances is rendered.\n       *\n       */\n      renderedItemCount: {\n        type: Number,\n        notify: !suppressTemplateNotifications,\n        readOnly: true\n      },\n\n      /**\n       * When greater than zero, defines an initial count of template instances\n       * to render after setting the `items` array, before the next paint, and\n       * puts the `dom-repeat` into \"chunking mode\".  The remaining items (and\n       * any future items as a result of pushing onto the array) will be created\n       * and rendered incrementally at each animation frame thereof until all\n       * instances have been rendered.\n       */\n      initialCount: {\n        type: Number\n      },\n\n      /**\n       * When `initialCount` is used, this property defines a frame rate (in\n       * fps) to target by throttling the number of instances rendered each\n       * frame to not exceed the budget for the target frame rate.  The\n       * framerate is effectively the number of `requestAnimationFrame`s that\n       * it tries to allow to actually fire in a given second. It does this\n       * by measuring the time between `rAF`s and continuously adjusting the\n       * number of items created each `rAF` to maintain the target framerate.\n       * Setting this to a higher number allows lower latency and higher\n       * throughput for event handlers and other tasks, but results in a\n       * longer time for the remaining items to complete rendering.\n       */\n      targetFramerate: {\n        type: Number,\n        value: 20\n      },\n\n      _targetFrameTime: {\n        type: Number,\n        computed: '__computeFrameTime(targetFramerate)'\n      },\n\n      /**\n       * When the global `suppressTemplateNotifications` setting is used, setting\n       * `notifyDomChange: true` will enable firing `dom-change` events on this\n       * element.\n       */\n      notifyDomChange: {\n        type: Boolean\n      },\n\n      /**\n       * When chunking is enabled via `initialCount` and the `items` array is\n       * set to a new array, this flag controls whether the previously rendered\n       * instances are reused or not.\n       *\n       * When `true`, any previously rendered template instances are updated in\n       * place to their new item values synchronously in one shot, and then any\n       * further items (if any) are chunked out.  When `false`, the list is\n       * returned back to its `initialCount` (any instances over the initial\n       * count are discarded) and the remainder of the list is chunked back in.\n       * Set this to `true` to avoid re-creating the list and losing scroll\n       * position, although note that when changing the list to completely\n       * different data the render thread will be blocked until all existing\n       * instances are updated to their new data.\n       */\n      reuseChunkedInstances: {\n        type: Boolean\n      }\n\n    };\n\n  }\n\n  static get observers() {\n    return [ '__itemsChanged(items.*)' ];\n  }\n\n  constructor() {\n    super();\n    this.__instances = [];\n    this.__renderDebouncer = null;\n    this.__itemsIdxToInstIdx = {};\n    this.__chunkCount = null;\n    this.__renderStartTime = null;\n    this.__itemsArrayChanged = false;\n    this.__shouldMeasureChunk = false;\n    this.__shouldContinueChunking = false;\n    this.__chunkingId = 0;\n    this.__sortFn = null;\n    this.__filterFn = null;\n    this.__observePaths = null;\n    /** @type {?function(new:TemplateInstanceBase, Object=)} */\n    this.__ctor = null;\n    this.__isDetached = true;\n    this.template = null;\n    /** @type {TemplateInfo} */\n    this._templateInfo;\n  }\n\n  /**\n   * @override\n   * @return {void}\n   */\n  disconnectedCallback() {\n    super.disconnectedCallback();\n    this.__isDetached = true;\n    for (let i=0; i<this.__instances.length; i++) {\n      this.__detachInstance(i);\n    }\n    // Stop chunking if one was in progress\n    if (this.__chunkingId) {\n      cancelAnimationFrame(this.__chunkingId);\n    }\n  }\n\n  /**\n   * @override\n   * @return {void}\n   */\n  connectedCallback() {\n    super.connectedCallback();\n    if (!hideElementsGlobally()) {\n      this.style.display = 'none';\n    }\n    // only perform attachment if the element was previously detached.\n    if (this.__isDetached) {\n      this.__isDetached = false;\n      let wrappedParent = wrap(wrap(this).parentNode);\n      for (let i=0; i<this.__instances.length; i++) {\n        this.__attachInstance(i, wrappedParent);\n      }\n      // Restart chunking if one was in progress when disconnected\n      if (this.__chunkingId) {\n        this.__render();\n      }\n    }\n  }\n\n  __ensureTemplatized() {\n    // Templatizing (generating the instance constructor) needs to wait\n    // until ready, since won't have its template content handed back to\n    // it until then\n    if (!this.__ctor) {\n      // When `removeNestedTemplates` is true, the \"template\" is the element\n      // itself, which has been given a `_templateInfo` property\n      const thisAsTemplate = /** @type {!HTMLTemplateElement} */ (\n          /** @type {!HTMLElement} */ (this));\n      let template = this.template = thisAsTemplate._templateInfo ?\n          thisAsTemplate :\n          /** @type {!HTMLTemplateElement} */ (this.querySelector('template'));\n      if (!template) {\n        // Wait until childList changes and template should be there by then\n        let observer = new MutationObserver(() => {\n          if (this.querySelector('template')) {\n            observer.disconnect();\n            this.__render();\n          } else {\n            throw new Error('dom-repeat requires a <template> child');\n          }\n        });\n        observer.observe(this, {childList: true});\n        return false;\n      }\n      // Template instance props that should be excluded from forwarding\n      let instanceProps = {};\n      instanceProps[this.as] = true;\n      instanceProps[this.indexAs] = true;\n      instanceProps[this.itemsIndexAs] = true;\n      this.__ctor = templatize(template, this, {\n        mutableData: this.mutableData,\n        parentModel: true,\n        instanceProps: instanceProps,\n        /**\n         * @this {DomRepeat}\n         * @param {string} prop Property to set\n         * @param {*} value Value to set property to\n         */\n        forwardHostProp: function(prop, value) {\n          let i$ = this.__instances;\n          for (let i=0, inst; (i<i$.length) && (inst=i$[i]); i++) {\n            inst.forwardHostProp(prop, value);\n          }\n        },\n        /**\n         * @this {DomRepeat}\n         * @param {Object} inst Instance to notify\n         * @param {string} prop Property to notify\n         * @param {*} value Value to notify\n         */\n        notifyInstanceProp: function(inst, prop, value) {\n          if (matches(this.as, prop)) {\n            let idx = inst[this.itemsIndexAs];\n            if (prop == this.as) {\n              this.items[idx] = value;\n            }\n            let path = translate(this.as, `${JSCompiler_renameProperty('items', this)}.${idx}`, prop);\n            this.notifyPath(path, value);\n          }\n        }\n      });\n    }\n    return true;\n  }\n\n  __getMethodHost() {\n    // Technically this should be the owner of the outermost template.\n    // In shadow dom, this is always getRootNode().host, but we can\n    // approximate this via cooperation with our dataHost always setting\n    // `_methodHost` as long as there were bindings (or id's) on this\n    // instance causing it to get a dataHost.\n    return this.__dataHost._methodHost || this.__dataHost;\n  }\n\n  __functionFromPropertyValue(functionOrMethodName) {\n    if (typeof functionOrMethodName === 'string') {\n      let methodName = functionOrMethodName;\n      let obj = this.__getMethodHost();\n      return function() { return obj[methodName].apply(obj, arguments); };\n    }\n\n    return functionOrMethodName;\n  }\n\n  __sortChanged(sort) {\n    this.__sortFn = this.__functionFromPropertyValue(sort);\n    if (this.items) { this.__debounceRender(this.__render); }\n  }\n\n  __filterChanged(filter) {\n    this.__filterFn = this.__functionFromPropertyValue(filter);\n    if (this.items) { this.__debounceRender(this.__render); }\n  }\n\n  __computeFrameTime(rate) {\n    return Math.ceil(1000/rate);\n  }\n\n  __observeChanged() {\n    this.__observePaths = this.observe &&\n      this.observe.replace('.*', '.').split(' ');\n  }\n\n  __handleObservedPaths(path) {\n    // Handle cases where path changes should cause a re-sort/filter\n    if (this.__sortFn || this.__filterFn) {\n      if (!path) {\n        // Always re-render if the item itself changed\n        this.__debounceRender(this.__render, this.delay);\n      } else if (this.__observePaths) {\n        // Otherwise, re-render if the path changed matches an observed path\n        let paths = this.__observePaths;\n        for (let i=0; i<paths.length; i++) {\n          if (path.indexOf(paths[i]) === 0) {\n            this.__debounceRender(this.__render, this.delay);\n          }\n        }\n      }\n    }\n  }\n\n  __itemsChanged(change) {\n    if (this.items && !Array.isArray(this.items)) {\n      console.warn('dom-repeat expected array for `items`, found', this.items);\n    }\n    // If path was to an item (e.g. 'items.3' or 'items.3.foo'), forward the\n    // path to that instance synchronously (returns false for non-item paths)\n    if (!this.__handleItemPath(change.path, change.value)) {\n      // Otherwise, the array was reset ('items') or spliced ('items.splices'),\n      // so queue a render.  Restart chunking when the items changed (for\n      // backward compatibility), unless `reuseChunkedInstances` option is set\n      if (change.path === 'items') {\n        this.__itemsArrayChanged = true;\n      }\n      this.__debounceRender(this.__render);\n    }\n  }\n\n  /**\n   * @param {function(this:DomRepeat)} fn Function to debounce.\n   * @param {number=} delay Delay in ms to debounce by.\n   */\n  __debounceRender(fn, delay = 0) {\n    this.__renderDebouncer = Debouncer.debounce(\n          this.__renderDebouncer\n        , delay > 0 ? timeOut.after(delay) : microTask\n        , fn.bind(this));\n    enqueueDebouncer(this.__renderDebouncer);\n  }\n\n  /**\n   * Forces the element to render its content. Normally rendering is\n   * asynchronous to a provoking change. This is done for efficiency so\n   * that multiple changes trigger only a single render. The render method\n   * should be called if, for example, template rendering is required to\n   * validate application state.\n   * @return {void}\n   */\n  render() {\n    // Queue this repeater, then flush all in order\n    this.__debounceRender(this.__render);\n    flush();\n  }\n\n  __render() {\n    if (!this.__ensureTemplatized()) {\n      // No template found yet\n      return;\n    }\n    let items = this.items || [];\n    // Sort and filter the items into a mapping array from instance->item\n    const isntIdxToItemsIdx = this.__sortAndFilterItems(items);\n    // If we're chunking, increase the limit if there are new instances to\n    // create and schedule the next chunk\n    const limit = this.__calculateLimit(isntIdxToItemsIdx.length);\n    // Create, update, and/or remove instances\n    this.__updateInstances(items, limit, isntIdxToItemsIdx);\n    // If we're chunking, schedule a rAF task to measure/continue chunking.     \n    // Do this before any notifying events (renderedItemCount & dom-change)\n    // since those could modify items and enqueue a new full render which will\n    // pre-empt this measurement.\n    if (this.initialCount &&\n       (this.__shouldMeasureChunk || this.__shouldContinueChunking)) {\n      cancelAnimationFrame(this.__chunkingId);\n      this.__chunkingId = requestAnimationFrame(() => {\n        this.__chunkingId = null;\n        this.__continueChunking();\n      });\n    }\n    // Set rendered item count\n    this._setRenderedItemCount(this.__instances.length);\n    // Notify users\n    if (!suppressTemplateNotifications || this.notifyDomChange) {\n      this.dispatchEvent(new CustomEvent('dom-change', {\n        bubbles: true,\n        composed: true\n      }));\n    }\n  }\n\n  __sortAndFilterItems(items) {\n    // Generate array maping the instance index to the items array index\n    let isntIdxToItemsIdx = new Array(items.length);\n    for (let i=0; i<items.length; i++) {\n      isntIdxToItemsIdx[i] = i;\n    }\n    // Apply user filter\n    if (this.__filterFn) {\n      isntIdxToItemsIdx = isntIdxToItemsIdx.filter((i, idx, array) =>\n        this.__filterFn(items[i], idx, array));\n    }\n    // Apply user sort\n    if (this.__sortFn) {\n      isntIdxToItemsIdx.sort((a, b) => this.__sortFn(items[a], items[b]));\n    }\n    return isntIdxToItemsIdx;\n  }\n\n  __calculateLimit(filteredItemCount) {\n    let limit = filteredItemCount;\n    const currentCount = this.__instances.length;\n    // When chunking, we increase the limit from the currently rendered count\n    // by the chunk count that is re-calculated after each rAF (with special\n    // cases for resetting the limit to initialCount after changing items)\n    if (this.initialCount) {\n      let newCount;\n      if (!this.__chunkCount ||\n        (this.__itemsArrayChanged && !this.reuseChunkedInstances)) {\n        // Limit next render to the initial count\n        limit = Math.min(filteredItemCount, this.initialCount);\n        // Subtract off any existing instances to determine the number of\n        // instances that will be created\n        newCount = Math.max(limit - currentCount, 0);\n        // Initialize the chunk size with how many items we're creating\n        this.__chunkCount = newCount || 1;\n      } else {\n        // The number of new instances that will be created is based on the\n        // existing instances, the new list size, and the chunk size\n        newCount = Math.min(\n          Math.max(filteredItemCount - currentCount, 0), \n          this.__chunkCount);\n        // Update the limit based on how many new items we're making, limited\n        // buy the total size of the list\n        limit = Math.min(currentCount + newCount, filteredItemCount);\n      }\n      // Record some state about chunking for use in `__continueChunking`\n      this.__shouldMeasureChunk = newCount === this.__chunkCount;\n      this.__shouldContinueChunking = limit < filteredItemCount;\n      this.__renderStartTime = performance.now();\n    }\n    this.__itemsArrayChanged = false;\n    return limit;\n  }\n\n  __continueChunking() {\n    // Simple auto chunkSize throttling algorithm based on feedback loop:\n    // measure actual time between frames and scale chunk count by ratio of\n    // target/actual frame time.  Only modify chunk size if our measurement\n    // reflects the cost of a creating a full chunk's worth of instances; this\n    // avoids scaling up the chunk size if we e.g. quickly re-rendered instances\n    // in place\n    if (this.__shouldMeasureChunk) {\n      const renderTime = performance.now() - this.__renderStartTime;\n      const ratio = this._targetFrameTime / renderTime;\n      this.__chunkCount = Math.round(this.__chunkCount * ratio) || 1;\n    }\n    // Enqueue a new render if we haven't reached the full size of the list\n    if (this.__shouldContinueChunking) {\n      this.__debounceRender(this.__render);\n    }\n  }\n  \n  __updateInstances(items, limit, isntIdxToItemsIdx) {\n    // items->inst map kept for item path forwarding\n    const itemsIdxToInstIdx = this.__itemsIdxToInstIdx = {};\n    let instIdx;\n    // Generate instances and assign items\n    for (instIdx=0; instIdx<limit; instIdx++) {\n      let inst = this.__instances[instIdx];\n      let itemIdx = isntIdxToItemsIdx[instIdx];\n      let item = items[itemIdx];\n      itemsIdxToInstIdx[itemIdx] = instIdx;\n      if (inst) {\n        inst._setPendingProperty(this.as, item);\n        inst._setPendingProperty(this.indexAs, instIdx);\n        inst._setPendingProperty(this.itemsIndexAs, itemIdx);\n        inst._flushProperties();\n      } else {\n        this.__insertInstance(item, instIdx, itemIdx);\n      }\n    }\n    // Remove any extra instances from previous state\n    for (let i=this.__instances.length-1; i>=instIdx; i--) {\n      this.__detachAndRemoveInstance(i);\n    }\n  }\n\n  __detachInstance(idx) {\n    let inst = this.__instances[idx];\n    const wrappedRoot = wrap(inst.root);\n    for (let i=0; i<inst.children.length; i++) {\n      let el = inst.children[i];\n      wrappedRoot.appendChild(el);\n    }\n    return inst;\n  }\n\n  __attachInstance(idx, parent) {\n    let inst = this.__instances[idx];\n    // Note, this is pre-wrapped as an optimization\n    parent.insertBefore(inst.root, this);\n  }\n\n  __detachAndRemoveInstance(idx) {\n    this.__detachInstance(idx);\n    this.__instances.splice(idx, 1);\n  }\n\n  __stampInstance(item, instIdx, itemIdx) {\n    let model = {};\n    model[this.as] = item;\n    model[this.indexAs] = instIdx;\n    model[this.itemsIndexAs] = itemIdx;\n    return new this.__ctor(model);\n  }\n\n  __insertInstance(item, instIdx, itemIdx) {\n    const inst = this.__stampInstance(item, instIdx, itemIdx);\n    let beforeRow = this.__instances[instIdx + 1];\n    let beforeNode = beforeRow ? beforeRow.children[0] : this;\n    wrap(wrap(this).parentNode).insertBefore(inst.root, beforeNode);\n    this.__instances[instIdx] = inst;\n    return inst;\n  }\n\n  // Implements extension point from Templatize mixin\n  /**\n   * Shows or hides the template instance top level child elements. For\n   * text nodes, `textContent` is removed while \"hidden\" and replaced when\n   * \"shown.\"\n   * @param {boolean} hidden Set to true to hide the children;\n   * set to false to show them.\n   * @return {void}\n   * @protected\n   */\n  _showHideChildren(hidden) {\n    for (let i=0; i<this.__instances.length; i++) {\n      this.__instances[i]._showHideChildren(hidden);\n    }\n  }\n\n  // Called as a side effect of a host items.<key>.<path> path change,\n  // responsible for notifying item.<path> changes to inst for key\n  __handleItemPath(path, value) {\n    let itemsPath = path.slice(6); // 'items.'.length == 6\n    let dot = itemsPath.indexOf('.');\n    let itemsIdx = dot < 0 ? itemsPath : itemsPath.substring(0, dot);\n    // If path was index into array...\n    if (itemsIdx == parseInt(itemsIdx, 10)) {\n      let itemSubPath = dot < 0 ? '' : itemsPath.substring(dot+1);\n      // If the path is observed, it will trigger a full refresh\n      this.__handleObservedPaths(itemSubPath);\n      // Note, even if a rull refresh is triggered, always do the path\n      // notification because unless mutableData is used for dom-repeat\n      // and all elements in the instance subtree, a full refresh may\n      // not trigger the proper update.\n      let instIdx = this.__itemsIdxToInstIdx[itemsIdx];\n      let inst = this.__instances[instIdx];\n      if (inst) {\n        let itemPath = this.as + (itemSubPath ? '.' + itemSubPath : '');\n        // This is effectively `notifyPath`, but avoids some of the overhead\n        // of the public API\n        inst._setPendingPropertyOrPath(itemPath, value, false, true);\n        inst._flushProperties();\n      }\n      return true;\n    }\n  }\n\n  /**\n   * Returns the item associated with a given element stamped by\n   * this `dom-repeat`.\n   *\n   * Note, to modify sub-properties of the item,\n   * `modelForElement(el).set('item.<sub-prop>', value)`\n   * should be used.\n   *\n   * @param {!HTMLElement} el Element for which to return the item.\n   * @return {*} Item associated with the element.\n   */\n  itemForElement(el) {\n    let instance = this.modelForElement(el);\n    return instance && instance[this.as];\n  }\n\n  /**\n   * Returns the inst index for a given element stamped by this `dom-repeat`.\n   * If `sort` is provided, the index will reflect the sorted order (rather\n   * than the original array order).\n   *\n   * @param {!HTMLElement} el Element for which to return the index.\n   * @return {?number} Row index associated with the element (note this may\n   *   not correspond to the array index if a user `sort` is applied).\n   */\n  indexForElement(el) {\n    let instance = this.modelForElement(el);\n    return instance && instance[this.indexAs];\n  }\n\n  /**\n   * Returns the template \"model\" associated with a given element, which\n   * serves as the binding scope for the template instance the element is\n   * contained in. A template model\n   * should be used to manipulate data associated with this template instance.\n   *\n   * Example:\n   *\n   *   let model = modelForElement(el);\n   *   if (model.index < 10) {\n   *     model.set('item.checked', true);\n   *   }\n   *\n   * @param {!HTMLElement} el Element for which to return a template model.\n   * @return {TemplateInstanceBase} Model representing the binding scope for\n   *   the element.\n   */\n  modelForElement(el) {\n    return modelForElement(this.template, el);\n  }\n\n}\n\ncustomElements.define(DomRepeat.is, DomRepeat);\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * Get ISO 8601 week number for the given date.\n *\n * @param {!Date} Date object\n * @return {number} Week number\n */\nexport function getISOWeekNumber(date) {\n  // Ported from Vaadin Framework method com.vaadin.client.DateTimeService.getISOWeekNumber(date)\n  let dayOfWeek = date.getDay(); // 0 == sunday\n\n  // ISO 8601 use weeks that start on monday so we use\n  // mon=1,tue=2,...sun=7;\n  if (dayOfWeek === 0) {\n    dayOfWeek = 7;\n  }\n  // Find nearest thursday (defines the week in ISO 8601). The week number\n  // for the nearest thursday is the same as for the target date.\n  const nearestThursdayDiff = 4 - dayOfWeek; // 4 is thursday\n  const nearestThursday = new Date(date.getTime() + nearestThursdayDiff * 24 * 3600 * 1000);\n\n  const firstOfJanuary = new Date(0, 0);\n  firstOfJanuary.setFullYear(nearestThursday.getFullYear());\n\n  const timeDiff = nearestThursday.getTime() - firstOfJanuary.getTime();\n\n  // Rounding the result, as the division doesn't result in an integer\n  // when the given date is inside daylight saving time period.\n  const daysSinceFirstOfJanuary = Math.round(timeDiff / (24 * 3600 * 1000));\n\n  return Math.floor(daysSinceFirstOfJanuary / 7 + 1);\n}\n\n/**\n * Check if two dates are equal.\n *\n * @param {Date} date1\n * @param {Date} date2\n * @return {boolean} True if the given date objects refer to the same date\n */\nexport function dateEquals(date1, date2) {\n  return (\n    date1 instanceof Date &&\n    date2 instanceof Date &&\n    date1.getFullYear() === date2.getFullYear() &&\n    date1.getMonth() === date2.getMonth() &&\n    date1.getDate() === date2.getDate()\n  );\n}\n\n/**\n * Check if the given date is in the range of allowed dates.\n *\n * @param {!Date} date The date to check\n * @param {Date} min Range start\n * @param {Date} max Range end\n * @return {boolean} True if the date is in the range\n */\nexport function dateAllowed(date, min, max) {\n  return (!min || date >= min) && (!max || date <= max);\n}\n\n/**\n * Get closest date from array of dates.\n *\n * @param {!Date} date The date to compare dates with\n * @param {!Array<!Date>} dates Array of date objects\n * @return {!Date} Closest date\n */\nexport function getClosestDate(date, dates) {\n  return dates\n    .filter((date) => date !== undefined)\n    .reduce((closestDate, candidate) => {\n      if (!candidate) {\n        return closestDate;\n      }\n\n      if (!closestDate) {\n        return candidate;\n      }\n\n      const candidateDiff = Math.abs(date.getTime() - candidate.getTime());\n      const closestDateDiff = Math.abs(closestDate.getTime() - date.getTime());\n      return candidateDiff < closestDateDiff ? candidate : closestDate;\n    });\n}\n\n/**\n * Extracts the basic component parts of a date (day, month and year)\n * to the expected format.\n * @param {!Date} date\n * @return {{day: number, month: number, year: number}}\n */\nexport function extractDateParts(date) {\n  return {\n    day: date.getDate(),\n    month: date.getMonth(),\n    year: date.getFullYear(),\n  };\n}\n\n/**\n * Get difference in months between today and given months value.\n *\n * @param {number} months\n * @return {number}\n */\nexport function dateAfterXMonths(months) {\n  const today = new Date();\n  const result = new Date(today);\n  result.setDate(1);\n  result.setMonth(parseInt(months) + today.getMonth());\n  return result;\n}\n\n/**\n * Calculate the year of the date based on the provided reference date.\n * Gets a two-digit year and returns a full year.\n * @param {!Date} referenceDate The date to act as basis in the calculation\n * @param {!number} year Should be in the range of [0, 99]\n * @param {number} month\n * @param {number} day\n * @return {!number} Adjusted year value\n */\nexport function getAdjustedYear(referenceDate, year, month = 0, day = 1) {\n  if (year > 99) {\n    throw new Error('The provided year cannot have more than 2 digits.');\n  }\n  if (year < 0) {\n    throw new Error('The provided year cannot be negative.');\n  }\n  // Year values up to 2 digits are parsed based on the reference date.\n  let adjustedYear = year + Math.floor(referenceDate.getFullYear() / 100) * 100;\n  if (referenceDate < new Date(adjustedYear - 50, month, day)) {\n    adjustedYear -= 100;\n  } else if (referenceDate > new Date(adjustedYear + 50, month, day)) {\n    adjustedYear += 100;\n  }\n  return adjustedYear;\n}\n\n/**\n * Parse date string of one of the following date formats:\n * - ISO 8601 `\"YYYY-MM-DD\"`\n * - 6-digit extended ISO 8601 `\"+YYYYYY-MM-DD\"`, `\"-YYYYYY-MM-DD\"`\n * @param {!string} str Date string to parse\n * @return {Date} Parsed date\n */\nexport function parseDate(str) {\n  // Parsing with RegExp to ensure correct format\n  const parts = /^([-+]\\d{1}|\\d{2,4}|[-+]\\d{6})-(\\d{1,2})-(\\d{1,2})$/u.exec(str);\n  if (!parts) {\n    return undefined;\n  }\n\n  const date = new Date(0, 0); // Wrong date (1900-01-01), but with midnight in local time\n  date.setFullYear(parseInt(parts[1], 10));\n  date.setMonth(parseInt(parts[2], 10) - 1);\n  date.setDate(parseInt(parts[3], 10));\n  return date;\n}\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '@polymer/polymer/lib/elements/dom-repeat.js';\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { FocusMixin } from '@vaadin/a11y-base/src/focus-mixin.js';\nimport { addListener } from '@vaadin/component-base/src/gestures.js';\nimport { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { dateAllowed, dateEquals, getISOWeekNumber } from './vaadin-date-picker-helper.js';\n\n/**\n * @extends HTMLElement\n * @private\n */\nclass MonthCalendar extends FocusMixin(ThemableMixin(PolymerElement)) {\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: block;\n        }\n\n        #monthGrid {\n          width: 100%;\n          border-collapse: collapse;\n        }\n\n        #days-container tr,\n        #weekdays-container tr {\n          display: flex;\n        }\n\n        [part~='date'] {\n          outline: none;\n        }\n\n        [part~='disabled'] {\n          pointer-events: none;\n        }\n\n        [part='week-number'][hidden],\n        [part='weekday'][hidden] {\n          display: none;\n        }\n\n        [part='weekday'],\n        [part~='date'] {\n          width: calc(100% / 7);\n          padding: 0;\n          font-weight: normal;\n        }\n\n        [part='weekday']:empty,\n        [part='week-number'] {\n          width: 12.5%;\n          flex-shrink: 0;\n          padding: 0;\n        }\n\n        :host([week-numbers]) [part='weekday']:not(:empty),\n        :host([week-numbers]) [part~='date'] {\n          width: 12.5%;\n        }\n\n        @media (forced-colors: active) {\n          [part~='date'][part~='focused'] {\n            outline: 1px solid;\n          }\n          [part~='date'][part~='selected'] {\n            outline: 3px solid;\n          }\n        }\n      </style>\n\n      <div part=\"month-header\" id=\"month-header\" aria-hidden=\"true\">[[_getTitle(month, i18n.monthNames)]]</div>\n      <table\n        id=\"monthGrid\"\n        role=\"grid\"\n        aria-labelledby=\"month-header\"\n        on-touchend=\"_preventDefault\"\n        on-touchstart=\"_onMonthGridTouchStart\"\n      >\n        <thead id=\"weekdays-container\">\n          <tr role=\"row\" part=\"weekdays\">\n            <th\n              part=\"weekday\"\n              aria-hidden=\"true\"\n              hidden$=\"[[!_showWeekSeparator(showWeekNumbers, i18n.firstDayOfWeek)]]\"\n            ></th>\n            <template\n              is=\"dom-repeat\"\n              items=\"[[_getWeekDayNames(i18n.weekdays, i18n.weekdaysShort, showWeekNumbers, i18n.firstDayOfWeek)]]\"\n            >\n              <th role=\"columnheader\" part=\"weekday\" scope=\"col\" abbr$=\"[[item.weekDay]]\" aria-hidden=\"true\">\n                [[item.weekDayShort]]\n              </th>\n            </template>\n          </tr>\n        </thead>\n        <tbody id=\"days-container\">\n          <template is=\"dom-repeat\" items=\"[[_weeks]]\" as=\"week\">\n            <tr role=\"row\">\n              <td\n                part=\"week-number\"\n                aria-hidden=\"true\"\n                hidden$=\"[[!_showWeekSeparator(showWeekNumbers, i18n.firstDayOfWeek)]]\"\n              >\n                [[__getWeekNumber(week)]]\n              </td>\n              <template is=\"dom-repeat\" items=\"[[week]]\">\n                <td\n                  role=\"gridcell\"\n                  part$=\"[[__getDatePart(item, focusedDate, selectedDate, minDate, maxDate)]]\"\n                  date=\"[[item]]\"\n                  tabindex$=\"[[__getDayTabindex(item, focusedDate)]]\"\n                  disabled$=\"[[__isDayDisabled(item, minDate, maxDate)]]\"\n                  aria-selected$=\"[[__getDayAriaSelected(item, selectedDate)]]\"\n                  aria-disabled$=\"[[__getDayAriaDisabled(item, minDate, maxDate)]]\"\n                  aria-label$=\"[[__getDayAriaLabel(item)]]\"\n                  >[[_getDate(item)]]</td\n                >\n              </template>\n            </tr>\n          </template>\n        </tbody>\n      </table>\n    `;\n  }\n\n  static get is() {\n    return 'vaadin-month-calendar';\n  }\n\n  static get properties() {\n    return {\n      /**\n       * A `Date` object defining the month to be displayed. Only year and\n       * month properties are actually used.\n       */\n      month: {\n        type: Date,\n        value: new Date(),\n      },\n\n      /**\n       * A `Date` object for the currently selected date.\n       */\n      selectedDate: {\n        type: Date,\n        notify: true,\n      },\n\n      /**\n       * A `Date` object for the currently focused date.\n       */\n      focusedDate: Date,\n\n      showWeekNumbers: {\n        type: Boolean,\n        value: false,\n      },\n\n      i18n: {\n        type: Object,\n      },\n\n      /**\n       * Flag stating whether taps on the component should be ignored.\n       */\n      ignoreTaps: Boolean,\n\n      _notTapping: Boolean,\n\n      /**\n       * The earliest date that can be selected. All earlier dates will be disabled.\n       */\n      minDate: {\n        type: Date,\n        value: null,\n      },\n\n      /**\n       * The latest date that can be selected. All later dates will be disabled.\n       */\n      maxDate: {\n        type: Date,\n        value: null,\n      },\n\n      _days: {\n        type: Array,\n        computed: '_getDays(month, i18n.firstDayOfWeek, minDate, maxDate)',\n      },\n\n      _weeks: {\n        type: Array,\n        computed: '_getWeeks(_days)',\n      },\n\n      disabled: {\n        type: Boolean,\n        reflectToAttribute: true,\n        computed: '_isDisabled(month, minDate, maxDate)',\n      },\n    };\n  }\n\n  static get observers() {\n    return [\n      '_showWeekNumbersChanged(showWeekNumbers, i18n.firstDayOfWeek)',\n      '__focusedDateChanged(focusedDate, _days)',\n    ];\n  }\n\n  get focusableDateElement() {\n    return [...this.shadowRoot.querySelectorAll('[part~=date]')].find((datePart) => {\n      return dateEquals(datePart.date, this.focusedDate);\n    });\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n    addListener(this.$.monthGrid, 'tap', this._handleTap.bind(this));\n  }\n\n  /* Returns true if all the dates in the month are out of the allowed range */\n  _isDisabled(month, minDate, maxDate) {\n    // First day of the month\n    const firstDate = new Date(0, 0);\n    firstDate.setFullYear(month.getFullYear());\n    firstDate.setMonth(month.getMonth());\n    firstDate.setDate(1);\n\n    // Last day of the month\n    const lastDate = new Date(0, 0);\n    lastDate.setFullYear(month.getFullYear());\n    lastDate.setMonth(month.getMonth() + 1);\n    lastDate.setDate(0);\n\n    if (\n      minDate &&\n      maxDate &&\n      minDate.getMonth() === maxDate.getMonth() &&\n      minDate.getMonth() === month.getMonth() &&\n      maxDate.getDate() - minDate.getDate() >= 0\n    ) {\n      return false;\n    }\n\n    return !dateAllowed(firstDate, minDate, maxDate) && !dateAllowed(lastDate, minDate, maxDate);\n  }\n\n  _getTitle(month, monthNames) {\n    if (month === undefined || monthNames === undefined) {\n      return;\n    }\n    return this.i18n.formatTitle(monthNames[month.getMonth()], month.getFullYear());\n  }\n\n  _onMonthGridTouchStart() {\n    this._notTapping = false;\n    setTimeout(() => {\n      this._notTapping = true;\n    }, 300);\n  }\n\n  _dateAdd(date, delta) {\n    date.setDate(date.getDate() + delta);\n  }\n\n  _applyFirstDayOfWeek(weekDayNames, firstDayOfWeek) {\n    if (weekDayNames === undefined || firstDayOfWeek === undefined) {\n      return;\n    }\n\n    return weekDayNames.slice(firstDayOfWeek).concat(weekDayNames.slice(0, firstDayOfWeek));\n  }\n\n  _getWeekDayNames(weekDayNames, weekDayNamesShort, showWeekNumbers, firstDayOfWeek) {\n    if (\n      weekDayNames === undefined ||\n      weekDayNamesShort === undefined ||\n      showWeekNumbers === undefined ||\n      firstDayOfWeek === undefined\n    ) {\n      return;\n    }\n    weekDayNames = this._applyFirstDayOfWeek(weekDayNames, firstDayOfWeek);\n    weekDayNamesShort = this._applyFirstDayOfWeek(weekDayNamesShort, firstDayOfWeek);\n    weekDayNames = weekDayNames.map((day, index) => {\n      return {\n        weekDay: day,\n        weekDayShort: weekDayNamesShort[index],\n      };\n    });\n\n    return weekDayNames;\n  }\n\n  __focusedDateChanged(focusedDate, days) {\n    if (days.some((date) => dateEquals(date, focusedDate))) {\n      this.removeAttribute('aria-hidden');\n    } else {\n      this.setAttribute('aria-hidden', 'true');\n    }\n  }\n\n  _getDate(date) {\n    return date ? date.getDate() : '';\n  }\n\n  _showWeekNumbersChanged(showWeekNumbers, firstDayOfWeek) {\n    if (showWeekNumbers && firstDayOfWeek === 1) {\n      this.setAttribute('week-numbers', '');\n    } else {\n      this.removeAttribute('week-numbers');\n    }\n  }\n\n  _showWeekSeparator(showWeekNumbers, firstDayOfWeek) {\n    // Currently only supported for locales that start the week on Monday.\n    return showWeekNumbers && firstDayOfWeek === 1;\n  }\n\n  _isToday(date) {\n    return dateEquals(new Date(), date);\n  }\n\n  _getDays(month, firstDayOfWeek) {\n    if (month === undefined || firstDayOfWeek === undefined) {\n      return;\n    }\n    // First day of the month (at midnight).\n    const date = new Date(0, 0);\n    date.setFullYear(month.getFullYear());\n    date.setMonth(month.getMonth());\n    date.setDate(1);\n\n    // Rewind to first day of the week.\n    while (date.getDay() !== firstDayOfWeek) {\n      this._dateAdd(date, -1);\n    }\n\n    const days = [];\n    const startMonth = date.getMonth();\n    const targetMonth = month.getMonth();\n    while (date.getMonth() === targetMonth || date.getMonth() === startMonth) {\n      days.push(date.getMonth() === targetMonth ? new Date(date.getTime()) : null);\n\n      // Advance to next day.\n      this._dateAdd(date, 1);\n    }\n    return days;\n  }\n\n  _getWeeks(days) {\n    return days.reduce((acc, day, i) => {\n      if (i % 7 === 0) {\n        acc.push([]);\n      }\n      acc[acc.length - 1].push(day);\n      return acc;\n    }, []);\n  }\n\n  _handleTap(e) {\n    if (!this.ignoreTaps && !this._notTapping && e.target.date && !e.target.hasAttribute('disabled')) {\n      this.selectedDate = e.target.date;\n      this.dispatchEvent(\n        new CustomEvent('date-tap', { detail: { date: e.target.date }, bubbles: true, composed: true }),\n      );\n    }\n  }\n\n  _preventDefault(e) {\n    e.preventDefault();\n  }\n\n  __getDatePart(date, focusedDate, selectedDate, minDate, maxDate) {\n    const result = ['date'];\n\n    if (this.__isDayDisabled(date, minDate, maxDate)) {\n      result.push('disabled');\n    }\n\n    if (this.__isDayFocused(date, focusedDate)) {\n      result.push('focused');\n    }\n\n    if (this.__isDaySelected(date, selectedDate)) {\n      result.push('selected');\n    }\n\n    if (this._isToday(date)) {\n      result.push('today');\n    }\n\n    return result.join(' ');\n  }\n\n  __getWeekNumber(days) {\n    const date = days.reduce((acc, d) => {\n      return !acc && d ? d : acc;\n    });\n\n    return getISOWeekNumber(date);\n  }\n\n  __isDayFocused(date, focusedDate) {\n    return dateEquals(date, focusedDate);\n  }\n\n  __isDaySelected(date, selectedDate) {\n    return dateEquals(date, selectedDate);\n  }\n\n  __getDayAriaSelected(date, selectedDate) {\n    if (this.__isDaySelected(date, selectedDate)) {\n      return 'true';\n    }\n  }\n\n  __isDayDisabled(date, minDate, maxDate) {\n    return !dateAllowed(date, minDate, maxDate);\n  }\n\n  __getDayAriaDisabled(date, min, max) {\n    if (date === undefined || min === undefined || max === undefined) {\n      return;\n    }\n\n    if (this.__isDayDisabled(date, min, max)) {\n      return 'true';\n    }\n  }\n\n  __getDayAriaLabel(date) {\n    if (!date) {\n      return '';\n    }\n\n    let ariaLabel = `${this._getDate(date)} ${this.i18n.monthNames[date.getMonth()]} ${date.getFullYear()}, ${\n      this.i18n.weekdays[date.getDay()]\n    }`;\n\n    if (this._isToday(date)) {\n      ariaLabel += `, ${this.i18n.today}`;\n    }\n\n    return ariaLabel;\n  }\n\n  __getDayTabindex(date, focusedDate) {\n    if (this.__isDayFocused(date, focusedDate)) {\n      return '0';\n    }\n\n    return '-1';\n  }\n}\n\ncustomElements.define(MonthCalendar.is, MonthCalendar);\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { afterNextRender } from '@polymer/polymer/lib/utils/render-status.js';\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { timeOut } from '@vaadin/component-base/src/async.js';\nimport { isFirefox } from '@vaadin/component-base/src/browser-utils.js';\nimport { Debouncer } from '@vaadin/component-base/src/debounce.js';\nimport { generateUniqueId } from '@vaadin/component-base/src/unique-id-utils.js';\n\n/**\n * @extends HTMLElement\n * @private\n */\nexport class InfiniteScroller extends PolymerElement {\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: block;\n          overflow: hidden;\n          height: 500px;\n        }\n\n        #scroller {\n          position: relative;\n          height: 100%;\n          overflow: auto;\n          outline: none;\n          margin-right: -40px;\n          -webkit-overflow-scrolling: touch;\n          overflow-x: hidden;\n        }\n\n        #scroller.notouchscroll {\n          -webkit-overflow-scrolling: auto;\n        }\n\n        #scroller::-webkit-scrollbar {\n          display: none;\n        }\n\n        .buffer {\n          position: absolute;\n          width: var(--vaadin-infinite-scroller-buffer-width, 100%);\n          box-sizing: border-box;\n          padding-right: 40px;\n          top: var(--vaadin-infinite-scroller-buffer-offset, 0);\n          animation: fadein 0.2s;\n        }\n\n        @keyframes fadein {\n          from {\n            opacity: 0;\n          }\n          to {\n            opacity: 1;\n          }\n        }\n      </style>\n\n      <div id=\"scroller\" on-scroll=\"_scroll\">\n        <div class=\"buffer\"></div>\n        <div class=\"buffer\"></div>\n        <div id=\"fullHeight\"></div>\n      </div>\n    `;\n  }\n\n  static get properties() {\n    return {\n      /**\n       * Count of individual items in each buffer.\n       * The scroller has 2 buffers altogether so bufferSize of 20\n       * will result in 40 buffered DOM items in total.\n       * Changing after initialization not supported.\n       */\n      bufferSize: {\n        type: Number,\n        value: 20,\n      },\n\n      /**\n       * The amount of initial scroll top. Needed in order for the\n       * user to be able to scroll backwards.\n       * @private\n       */\n      _initialScroll: {\n        value: 500000,\n      },\n\n      /**\n       * The index/position mapped at _initialScroll point.\n       * @private\n       */\n      _initialIndex: {\n        value: 0,\n      },\n\n      /** @private */\n      _buffers: Array,\n\n      /** @private */\n      _preventScrollEvent: Boolean,\n\n      /** @private */\n      _mayHaveMomentum: Boolean,\n\n      /** @private */\n      _initialized: Boolean,\n\n      active: {\n        type: Boolean,\n        observer: '_activated',\n      },\n    };\n  }\n\n  /**\n   * @return {number}\n   */\n  get bufferOffset() {\n    return this._buffers[0].offsetTop;\n  }\n\n  /**\n   * @return {number}\n   */\n  get itemHeight() {\n    if (!this._itemHeightVal) {\n      const itemHeight = getComputedStyle(this).getPropertyValue('--vaadin-infinite-scroller-item-height');\n      // Use background-position temp inline style for unit conversion\n      const tmpStyleProp = 'background-position';\n      this.$.fullHeight.style.setProperty(tmpStyleProp, itemHeight);\n      const itemHeightPx = getComputedStyle(this.$.fullHeight).getPropertyValue(tmpStyleProp);\n      this.$.fullHeight.style.removeProperty(tmpStyleProp);\n      this._itemHeightVal = parseFloat(itemHeightPx);\n    }\n\n    return this._itemHeightVal;\n  }\n\n  /** @private */\n  get _bufferHeight() {\n    return this.itemHeight * this.bufferSize;\n  }\n\n  /**\n   * @return {number}\n   */\n  get position() {\n    return (this.$.scroller.scrollTop - this._buffers[0].translateY) / this.itemHeight + this._firstIndex;\n  }\n\n  /**\n   * Current scroller position as index. Can be a fractional number.\n   *\n   * @type {number}\n   */\n  set position(index) {\n    this._preventScrollEvent = true;\n    if (index > this._firstIndex && index < this._firstIndex + this.bufferSize * 2) {\n      this.$.scroller.scrollTop = this.itemHeight * (index - this._firstIndex) + this._buffers[0].translateY;\n    } else {\n      this._initialIndex = ~~index;\n      this._reset();\n      this._scrollDisabled = true;\n      this.$.scroller.scrollTop += (index % 1) * this.itemHeight;\n      this._scrollDisabled = false;\n    }\n\n    if (this._mayHaveMomentum) {\n      // Stop the possible iOS Safari momentum with -webkit-overflow-scrolling: auto;\n      this.$.scroller.classList.add('notouchscroll');\n      this._mayHaveMomentum = false;\n\n      setTimeout(() => {\n        // Restore -webkit-overflow-scrolling: touch; after a small delay.\n        this.$.scroller.classList.remove('notouchscroll');\n      }, 10);\n    }\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n\n    this._buffers = [...this.shadowRoot.querySelectorAll('.buffer')];\n\n    this.$.fullHeight.style.height = `${this._initialScroll * 2}px`;\n\n    // Firefox interprets elements with overflow:auto as focusable\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1069739\n    if (isFirefox) {\n      this.$.scroller.tabIndex = -1;\n    }\n  }\n\n  /**\n   * Force the scroller to update clones after a reset, without\n   * waiting for the debouncer to resolve.\n   */\n  forceUpdate() {\n    if (this._debouncerUpdateClones) {\n      this._buffers[0].updated = this._buffers[1].updated = false;\n      this._updateClones();\n      this._debouncerUpdateClones.cancel();\n    }\n  }\n\n  /**\n   * @protected\n   * @override\n   */\n  _createElement() {\n    // To be implemented.\n  }\n\n  /**\n   * @param {HTMLElement} _element\n   * @param {number} _index\n   * @protected\n   * @override\n   */\n  _updateElement(_element, _index) {\n    // To be implemented.\n  }\n\n  /** @private */\n  _activated(active) {\n    if (active && !this._initialized) {\n      this._createPool();\n      this._initialized = true;\n    }\n  }\n\n  /** @private */\n  _finishInit() {\n    if (!this._initDone) {\n      // Once the first set of items start fading in, stamp the rest\n      this._buffers.forEach((buffer) => {\n        [...buffer.children].forEach((slot) => {\n          this._ensureStampedInstance(slot._itemWrapper);\n        });\n      });\n\n      if (!this._buffers[0].translateY) {\n        this._reset();\n      }\n\n      this._initDone = true;\n      this.dispatchEvent(new CustomEvent('init-done'));\n    }\n  }\n\n  /** @private */\n  _translateBuffer(up) {\n    const index = up ? 1 : 0;\n    this._buffers[index].translateY = this._buffers[index ? 0 : 1].translateY + this._bufferHeight * (index ? -1 : 1);\n    this._buffers[index].style.transform = `translate3d(0, ${this._buffers[index].translateY}px, 0)`;\n    this._buffers[index].updated = false;\n    this._buffers.reverse();\n  }\n\n  /** @private */\n  _scroll() {\n    if (this._scrollDisabled) {\n      return;\n    }\n\n    const scrollTop = this.$.scroller.scrollTop;\n    if (scrollTop < this._bufferHeight || scrollTop > this._initialScroll * 2 - this._bufferHeight) {\n      // Scrolled near the end/beginning of the scrollable area -> reset.\n      this._initialIndex = ~~this.position;\n      this._reset();\n    }\n\n    // Check if we scrolled enough to translate the buffer positions.\n    const offset = this.itemHeight + this.bufferOffset;\n    const upperThresholdReached = scrollTop > this._buffers[1].translateY + offset;\n    const lowerThresholdReached = scrollTop < this._buffers[0].translateY + offset;\n\n    if (upperThresholdReached || lowerThresholdReached) {\n      this._translateBuffer(lowerThresholdReached);\n      this._updateClones();\n    }\n\n    if (!this._preventScrollEvent) {\n      this.dispatchEvent(new CustomEvent('custom-scroll', { bubbles: false, composed: true }));\n      this._mayHaveMomentum = true;\n    }\n    this._preventScrollEvent = false;\n\n    this._debouncerScrollFinish = Debouncer.debounce(this._debouncerScrollFinish, timeOut.after(200), () => {\n      const scrollerRect = this.$.scroller.getBoundingClientRect();\n      if (!this._isVisible(this._buffers[0], scrollerRect) && !this._isVisible(this._buffers[1], scrollerRect)) {\n        this.position = this.position; // eslint-disable-line no-self-assign\n      }\n    });\n  }\n\n  /** @private */\n  _reset() {\n    this._scrollDisabled = true;\n    this.$.scroller.scrollTop = this._initialScroll;\n    this._buffers[0].translateY = this._initialScroll - this._bufferHeight;\n    this._buffers[1].translateY = this._initialScroll;\n    this._buffers.forEach((buffer) => {\n      buffer.style.transform = `translate3d(0, ${buffer.translateY}px, 0)`;\n    });\n    this._buffers[0].updated = this._buffers[1].updated = false;\n    this._updateClones(true);\n\n    this._debouncerUpdateClones = Debouncer.debounce(this._debouncerUpdateClones, timeOut.after(200), () => {\n      this._buffers[0].updated = this._buffers[1].updated = false;\n      this._updateClones();\n    });\n\n    this._scrollDisabled = false;\n  }\n\n  /** @private */\n  _createPool() {\n    const container = this.getBoundingClientRect();\n    this._buffers.forEach((buffer) => {\n      for (let i = 0; i < this.bufferSize; i++) {\n        const itemWrapper = document.createElement('div');\n        itemWrapper.style.height = `${this.itemHeight}px`;\n        itemWrapper.instance = {};\n\n        const slotName = `vaadin-infinite-scroller-item-content-${generateUniqueId()}`;\n\n        const slot = document.createElement('slot');\n        slot.setAttribute('name', slotName);\n        slot._itemWrapper = itemWrapper;\n        buffer.appendChild(slot);\n\n        itemWrapper.setAttribute('slot', slotName);\n        this.appendChild(itemWrapper);\n\n        // Only stamp the visible instances first\n        if (this._isVisible(itemWrapper, container)) {\n          this._ensureStampedInstance(itemWrapper);\n        }\n      }\n    });\n\n    afterNextRender(this, () => {\n      this._finishInit();\n    });\n  }\n\n  /** @private */\n  _ensureStampedInstance(itemWrapper) {\n    if (itemWrapper.firstElementChild) {\n      return;\n    }\n\n    const tmpInstance = itemWrapper.instance;\n\n    itemWrapper.instance = this._createElement();\n    itemWrapper.appendChild(itemWrapper.instance);\n\n    Object.keys(tmpInstance).forEach((prop) => {\n      itemWrapper.instance.set(prop, tmpInstance[prop]);\n    });\n  }\n\n  /** @private */\n  _updateClones(viewPortOnly) {\n    this._firstIndex = ~~((this._buffers[0].translateY - this._initialScroll) / this.itemHeight) + this._initialIndex;\n\n    const scrollerRect = viewPortOnly ? this.$.scroller.getBoundingClientRect() : undefined;\n    this._buffers.forEach((buffer, bufferIndex) => {\n      if (!buffer.updated) {\n        const firstIndex = this._firstIndex + this.bufferSize * bufferIndex;\n\n        [...buffer.children].forEach((slot, index) => {\n          const itemWrapper = slot._itemWrapper;\n          if (!viewPortOnly || this._isVisible(itemWrapper, scrollerRect)) {\n            this._updateElement(itemWrapper.instance, firstIndex + index);\n          }\n        });\n        buffer.updated = true;\n      }\n    });\n  }\n\n  /** @private */\n  _isVisible(element, container) {\n    const rect = element.getBoundingClientRect();\n    return rect.bottom > container.top && rect.top < container.bottom;\n  }\n}\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { html } from '@polymer/polymer/lib/utils/html-tag.js';\nimport { dateAfterXMonths } from './vaadin-date-picker-helper.js';\nimport { InfiniteScroller } from './vaadin-infinite-scroller.js';\n\nconst stylesTemplate = html`\n  <style>\n    :host {\n      --vaadin-infinite-scroller-item-height: 270px;\n      position: absolute;\n      top: 0;\n      left: 0;\n      right: 0;\n      bottom: 0;\n      height: 100%;\n    }\n  </style>\n`;\n\nlet memoizedTemplate;\n\n/**\n * An element used internally by `<vaadin-date-picker>`. Not intended to be used separately.\n *\n * @extends InfiniteScroller\n * @private\n */\nclass DatePickerMonthScroller extends InfiniteScroller {\n  static get is() {\n    return 'vaadin-date-picker-month-scroller';\n  }\n\n  static get template() {\n    if (!memoizedTemplate) {\n      memoizedTemplate = super.template.cloneNode(true);\n      memoizedTemplate.content.appendChild(stylesTemplate.content.cloneNode(true));\n    }\n\n    return memoizedTemplate;\n  }\n\n  static get properties() {\n    return {\n      bufferSize: {\n        type: Number,\n        value: 3,\n      },\n    };\n  }\n\n  /**\n   * @protected\n   * @override\n   */\n  _createElement() {\n    return document.createElement('vaadin-month-calendar');\n  }\n\n  /**\n   * @param {HTMLElement} element\n   * @param {number} index\n   * @protected\n   * @override\n   */\n  _updateElement(element, index) {\n    element.month = dateAfterXMonths(index);\n  }\n}\n\ncustomElements.define(DatePickerMonthScroller.is, DatePickerMonthScroller);\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { html } from '@polymer/polymer/lib/utils/html-tag.js';\nimport { InfiniteScroller } from './vaadin-infinite-scroller.js';\n\nconst stylesTemplate = html`\n  <style>\n    :host {\n      --vaadin-infinite-scroller-item-height: 80px;\n      width: 50px;\n      display: block;\n      height: 100%;\n      position: absolute;\n      right: 0;\n      transform: translateX(100%);\n      -webkit-tap-highlight-color: transparent;\n      -webkit-user-select: none;\n      -moz-user-select: none;\n      user-select: none;\n      /* Center the year scroller position. */\n      --vaadin-infinite-scroller-buffer-offset: 50%;\n    }\n\n    :host::before {\n      content: '';\n      display: block;\n      background: transparent;\n      width: 0;\n      height: 0;\n      position: absolute;\n      left: 0;\n      top: 50%;\n      transform: translateY(-50%);\n      border-width: 6px;\n      border-style: solid;\n      border-color: transparent;\n      border-left-color: #000;\n    }\n  </style>\n`;\n\nlet memoizedTemplate;\n\n/**\n * An element used internally by `<vaadin-date-picker>`. Not intended to be used separately.\n *\n * @extends InfiniteScroller\n * @mixes ThemableMixin\n * @private\n */\nclass DatePickerYearScroller extends InfiniteScroller {\n  static get is() {\n    return 'vaadin-date-picker-year-scroller';\n  }\n\n  static get template() {\n    if (!memoizedTemplate) {\n      memoizedTemplate = super.template.cloneNode(true);\n      memoizedTemplate.content.appendChild(stylesTemplate.content.cloneNode(true));\n    }\n\n    return memoizedTemplate;\n  }\n\n  static get properties() {\n    return {\n      bufferSize: {\n        type: Number,\n        value: 12,\n      },\n    };\n  }\n\n  /**\n   * @protected\n   * @override\n   */\n  _createElement() {\n    return document.createElement('vaadin-date-picker-year');\n  }\n\n  /**\n   * @param {HTMLElement} element\n   * @param {number} index\n   * @protected\n   * @override\n   */\n  _updateElement(element, index) {\n    element.year = this._yearAfterXYears(index);\n  }\n\n  /** @private */\n  _yearAfterXYears(index) {\n    const today = new Date();\n    const result = new Date(today);\n    result.setFullYear(parseInt(index) + today.getFullYear());\n    return result.getFullYear();\n  }\n}\n\ncustomElements.define(DatePickerYearScroller.is, DatePickerYearScroller);\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\n/**\n * An element used internally by `<vaadin-date-picker>`. Not intended to be used separately.\n *\n * @extends HTMLElement\n * @mixes ThemableMixin\n * @private\n */\nexport class DatePickerYear extends ThemableMixin(PolymerElement) {\n  static get is() {\n    return 'vaadin-date-picker-year';\n  }\n\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: block;\n          height: 100%;\n        }\n      </style>\n      <div part=\"year-number\">[[year]]</div>\n      <div part=\"year-separator\" aria-hidden=\"true\"></div>\n    `;\n  }\n\n  static get properties() {\n    return {\n      year: {\n        type: String,\n      },\n\n      selectedDate: {\n        type: Object,\n      },\n    };\n  }\n\n  static get observers() {\n    return ['__updateSelected(year, selectedDate)'];\n  }\n\n  /** @private */\n  __updateSelected(year, selectedDate) {\n    this.toggleAttribute('selected', selectedDate && selectedDate.getFullYear() === year);\n    this.toggleAttribute('current', year === new Date().getFullYear());\n  }\n}\n\ncustomElements.define(DatePickerYear.is, DatePickerYear);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * A controller for listening on media query changes.\n */\nexport class MediaQueryController {\n  constructor(query, callback) {\n    /**\n     * The CSS media query to evaluate.\n     *\n     * @type {string}\n     * @protected\n     */\n    this.query = query;\n\n    /**\n     * Function to call when media query changes.\n     *\n     * @type {Function}\n     * @protected\n     */\n    this.callback = callback;\n\n    this._boundQueryHandler = this._queryHandler.bind(this);\n  }\n\n  hostConnected() {\n    this._removeListener();\n\n    this._mediaQuery = window.matchMedia(this.query);\n\n    this._addListener();\n\n    this._queryHandler(this._mediaQuery);\n  }\n\n  hostDisconnected() {\n    this._removeListener();\n  }\n\n  /** @private */\n  _addListener() {\n    if (this._mediaQuery) {\n      this._mediaQuery.addListener(this._boundQueryHandler);\n    }\n  }\n\n  /** @private */\n  _removeListener() {\n    if (this._mediaQuery) {\n      this._mediaQuery.removeListener(this._boundQueryHandler);\n    }\n\n    this._mediaQuery = null;\n  }\n\n  /** @private */\n  _queryHandler(mediaQuery) {\n    if (typeof this.callback === 'function') {\n      this.callback(mediaQuery.matches);\n    }\n  }\n}\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '@vaadin/button/src/vaadin-button.js';\nimport './vaadin-month-calendar.js';\nimport './vaadin-date-picker-month-scroller.js';\nimport './vaadin-date-picker-year-scroller.js';\nimport './vaadin-date-picker-year.js';\nimport { flush } from '@polymer/polymer/lib/utils/flush.js';\nimport { afterNextRender } from '@polymer/polymer/lib/utils/render-status.js';\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { timeOut } from '@vaadin/component-base/src/async.js';\nimport { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';\nimport { Debouncer } from '@vaadin/component-base/src/debounce.js';\nimport { DirMixin } from '@vaadin/component-base/src/dir-mixin.js';\nimport { addListener, setTouchAction } from '@vaadin/component-base/src/gestures.js';\nimport { MediaQueryController } from '@vaadin/component-base/src/media-query-controller.js';\nimport { SlotController } from '@vaadin/component-base/src/slot-controller.js';\nimport { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { dateAfterXMonths, dateEquals, extractDateParts, getClosestDate } from './vaadin-date-picker-helper.js';\n\n/**\n * @extends HTMLElement\n * @private\n */\nclass DatePickerOverlayContent extends ControllerMixin(ThemableMixin(DirMixin(PolymerElement))) {\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: flex;\n          flex-direction: column;\n          height: 100%;\n          width: 100%;\n          outline: none;\n        }\n\n        [part='overlay-header'] {\n          display: flex;\n          flex-shrink: 0;\n          flex-wrap: nowrap;\n          align-items: center;\n        }\n\n        :host(:not([fullscreen])) [part='overlay-header'] {\n          display: none;\n        }\n\n        [part='label'] {\n          flex-grow: 1;\n        }\n\n        [hidden] {\n          display: none !important;\n        }\n\n        [part='years-toggle-button'] {\n          display: flex;\n        }\n\n        #scrollers {\n          display: flex;\n          height: 100%;\n          width: 100%;\n          position: relative;\n          overflow: hidden;\n        }\n\n        :host([desktop]) ::slotted([slot='months']) {\n          right: 50px;\n          transform: none !important;\n        }\n\n        :host([desktop]) ::slotted([slot='years']) {\n          transform: none !important;\n        }\n\n        :host(.animate) ::slotted([slot='months']),\n        :host(.animate) ::slotted([slot='years']) {\n          transition: all 200ms;\n        }\n\n        [part='toolbar'] {\n          display: flex;\n          justify-content: space-between;\n          z-index: 2;\n          flex-shrink: 0;\n        }\n      </style>\n\n      <div part=\"overlay-header\" on-touchend=\"_preventDefault\" aria-hidden=\"true\">\n        <div part=\"label\">[[_formatDisplayed(selectedDate, i18n.formatDate, label)]]</div>\n        <div part=\"clear-button\" hidden$=\"[[!selectedDate]]\"></div>\n        <div part=\"toggle-button\"></div>\n\n        <div part=\"years-toggle-button\" hidden$=\"[[_desktopMode]]\" aria-hidden=\"true\">\n          [[_yearAfterXMonths(_visibleMonthIndex)]]\n        </div>\n      </div>\n\n      <div id=\"scrollers\">\n        <slot name=\"months\"></slot>\n        <slot name=\"years\"></slot>\n      </div>\n\n      <div on-touchend=\"_preventDefault\" role=\"toolbar\" part=\"toolbar\">\n        <slot name=\"today-button\"></slot>\n        <slot name=\"cancel-button\"></slot>\n      </div>\n    `;\n  }\n\n  static get is() {\n    return 'vaadin-date-picker-overlay-content';\n  }\n\n  static get properties() {\n    return {\n      scrollDuration: {\n        type: Number,\n        value: 300,\n      },\n\n      /**\n       * The value for this element.\n       */\n      selectedDate: {\n        type: Date,\n        value: null,\n      },\n\n      /**\n       * Date value which is focused using keyboard.\n       */\n      focusedDate: {\n        type: Date,\n        notify: true,\n        observer: '_focusedDateChanged',\n      },\n\n      _focusedMonthDate: Number,\n\n      /**\n       * Date which should be visible when there is no value selected.\n       */\n      initialPosition: {\n        type: Date,\n        observer: '_initialPositionChanged',\n      },\n\n      _originDate: {\n        value: new Date(),\n      },\n\n      _visibleMonthIndex: Number,\n\n      _desktopMode: {\n        type: Boolean,\n        observer: '_desktopModeChanged',\n      },\n\n      _desktopMediaQuery: {\n        type: String,\n        value: '(min-width: 375px)',\n      },\n\n      _translateX: {\n        observer: '_translateXChanged',\n      },\n\n      _yearScrollerWidth: {\n        value: 50,\n      },\n\n      i18n: {\n        type: Object,\n      },\n\n      showWeekNumbers: {\n        type: Boolean,\n        value: false,\n      },\n\n      _ignoreTaps: Boolean,\n\n      _notTapping: Boolean,\n\n      /**\n       * The earliest date that can be selected. All earlier dates will be disabled.\n       */\n      minDate: Date,\n\n      /**\n       * The latest date that can be selected. All later dates will be disabled.\n       */\n      maxDate: Date,\n\n      /**\n       * Input label\n       */\n      label: String,\n\n      _cancelButton: {\n        type: Object,\n      },\n\n      _todayButton: {\n        type: Object,\n      },\n\n      calendars: {\n        type: Array,\n        value: () => [],\n      },\n\n      years: {\n        type: Array,\n        value: () => [],\n      },\n    };\n  }\n\n  static get observers() {\n    return [\n      '__updateCalendars(calendars, i18n, minDate, maxDate, selectedDate, focusedDate, showWeekNumbers, _ignoreTaps, _theme)',\n      '__updateCancelButton(_cancelButton, i18n)',\n      '__updateTodayButton(_todayButton, i18n, minDate, maxDate)',\n      '__updateYears(years, selectedDate, _theme)',\n    ];\n  }\n\n  /**\n   * Whether to scroll to a sub-month position when scrolling to a date.\n   * This is active if the month scroller is not large enough to fit a\n   * full month. In that case we want to scroll to a position between\n   * two months in order to have the focused date in the visible area.\n   * @returns {boolean} whether to use sub-month scrolling\n   * @private\n   */\n  get __useSubMonthScrolling() {\n    return this._monthScroller.clientHeight < this._monthScroller.itemHeight + this._monthScroller.bufferOffset;\n  }\n\n  get focusableDateElement() {\n    return this.calendars.map((calendar) => calendar.focusableDateElement).find(Boolean);\n  }\n\n  ready() {\n    super.ready();\n\n    this.setAttribute('role', 'dialog');\n\n    addListener(this.$.scrollers, 'track', this._track.bind(this));\n    addListener(this.shadowRoot.querySelector('[part=\"clear-button\"]'), 'tap', this._clear.bind(this));\n    addListener(this.shadowRoot.querySelector('[part=\"toggle-button\"]'), 'tap', this._cancel.bind(this));\n    addListener(\n      this.shadowRoot.querySelector('[part=\"years-toggle-button\"]'),\n      'tap',\n      this._toggleYearScroller.bind(this),\n    );\n\n    this.addController(\n      new MediaQueryController(this._desktopMediaQuery, (matches) => {\n        this._desktopMode = matches;\n      }),\n    );\n\n    this.addController(\n      new SlotController(this, 'today-button', 'vaadin-button', {\n        observe: false,\n        initializer: (btn) => {\n          btn.setAttribute('theme', 'tertiary');\n          btn.addEventListener('keydown', (e) => this.__onTodayButtonKeyDown(e));\n          addListener(btn, 'tap', this._onTodayTap.bind(this));\n          this._todayButton = btn;\n        },\n      }),\n    );\n\n    this.addController(\n      new SlotController(this, 'cancel-button', 'vaadin-button', {\n        observe: false,\n        initializer: (btn) => {\n          btn.setAttribute('theme', 'tertiary');\n          btn.addEventListener('keydown', (e) => this.__onCancelButtonKeyDown(e));\n          addListener(btn, 'tap', this._cancel.bind(this));\n          this._cancelButton = btn;\n        },\n      }),\n    );\n\n    this.__initMonthScroller();\n    this.__initYearScroller();\n  }\n\n  /**\n   * Fired when the scroller reaches the target scrolling position.\n   * @event scroll-animation-finished\n   * @param {Number} detail.position new position\n   * @param {Number} detail.oldPosition old position\n   */\n\n  connectedCallback() {\n    super.connectedCallback();\n    this._closeYearScroller();\n    this._toggleAnimateClass(true);\n    setTouchAction(this.$.scrollers, 'pan-y');\n  }\n\n  /**\n   * Focuses the cancel button\n   */\n  focusCancel() {\n    this._cancelButton.focus();\n  }\n\n  /**\n   * Scrolls the list to the given Date.\n   */\n  scrollToDate(date, animate) {\n    const offset = this.__useSubMonthScrolling ? this._calculateWeekScrollOffset(date) : 0;\n    this._scrollToPosition(this._differenceInMonths(date, this._originDate) + offset, animate);\n    this._monthScroller.forceUpdate();\n  }\n\n  __initMonthScroller() {\n    this.addController(\n      new SlotController(this, 'months', 'vaadin-date-picker-month-scroller', {\n        observe: false,\n        initializer: (scroller) => {\n          scroller.addEventListener('custom-scroll', () => {\n            this._onMonthScroll();\n          });\n\n          scroller.addEventListener('touchstart', () => {\n            this._onMonthScrollTouchStart();\n          });\n\n          scroller.addEventListener('keydown', (e) => {\n            this.__onMonthCalendarKeyDown(e);\n          });\n\n          scroller.addEventListener('init-done', () => {\n            const calendars = [...this.querySelectorAll('vaadin-month-calendar')];\n\n            // Two-way binding for selectedDate property\n            calendars.forEach((calendar) => {\n              calendar.addEventListener('selected-date-changed', (e) => {\n                this.selectedDate = e.detail.value;\n              });\n            });\n\n            this.calendars = calendars;\n          });\n\n          this._monthScroller = scroller;\n        },\n      }),\n    );\n  }\n\n  __initYearScroller() {\n    this.addController(\n      new SlotController(this, 'years', 'vaadin-date-picker-year-scroller', {\n        observe: false,\n        initializer: (scroller) => {\n          scroller.setAttribute('aria-hidden', 'true');\n\n          addListener(scroller, 'tap', (e) => {\n            this._onYearTap(e);\n          });\n\n          scroller.addEventListener('custom-scroll', () => {\n            this._onYearScroll();\n          });\n\n          scroller.addEventListener('touchstart', () => {\n            this._onYearScrollTouchStart();\n          });\n\n          scroller.addEventListener('init-done', () => {\n            this.years = [...this.querySelectorAll('vaadin-date-picker-year')];\n          });\n\n          this._yearScroller = scroller;\n        },\n      }),\n    );\n  }\n\n  __updateCancelButton(cancelButton, i18n) {\n    if (cancelButton) {\n      cancelButton.textContent = i18n && i18n.cancel;\n    }\n  }\n\n  __updateTodayButton(todayButton, i18n, minDate, maxDate) {\n    if (todayButton) {\n      todayButton.textContent = i18n && i18n.today;\n      todayButton.disabled = !this._isTodayAllowed(minDate, maxDate);\n    }\n  }\n\n  // eslint-disable-next-line max-params\n  __updateCalendars(calendars, i18n, minDate, maxDate, selectedDate, focusedDate, showWeekNumbers, ignoreTaps, theme) {\n    if (calendars && calendars.length) {\n      calendars.forEach((calendar) => {\n        calendar.setProperties({\n          i18n,\n          minDate,\n          maxDate,\n          focusedDate,\n          selectedDate,\n          showWeekNumbers,\n          ignoreTaps,\n        });\n\n        if (theme) {\n          calendar.setAttribute('theme', theme);\n        } else {\n          calendar.removeAttribute('theme');\n        }\n      });\n    }\n  }\n\n  __updateYears(years, selectedDate, theme) {\n    if (years && years.length) {\n      years.forEach((year) => {\n        year.selectedDate = selectedDate;\n\n        if (theme) {\n          year.setAttribute('theme', theme);\n        } else {\n          year.removeAttribute('theme');\n        }\n      });\n    }\n  }\n\n  /**\n   * Select a date and fire event indicating user interaction.\n   * @protected\n   */\n  _selectDate(dateToSelect) {\n    this.selectedDate = dateToSelect;\n    this.dispatchEvent(\n      new CustomEvent('date-selected', { detail: { date: dateToSelect }, bubbles: true, composed: true }),\n    );\n  }\n\n  _desktopModeChanged(desktopMode) {\n    this.toggleAttribute('desktop', desktopMode);\n  }\n\n  _focusedDateChanged(focusedDate) {\n    this.revealDate(focusedDate);\n  }\n\n  /**\n   * Scrolls the month and year scrollers enough to reveal the given date.\n   */\n  revealDate(date, animate = true) {\n    if (!date) {\n      return;\n    }\n    const diff = this._differenceInMonths(date, this._originDate);\n    // If scroll area does not fit the full month, then always scroll with an offset to\n    // approximately display the week of the date\n    if (this.__useSubMonthScrolling) {\n      const offset = this._calculateWeekScrollOffset(date);\n      this._scrollToPosition(diff + offset, animate);\n      return;\n    }\n\n    // Otherwise determine if we need to scroll to make the month of the date visible\n    const scrolledAboveViewport = this._monthScroller.position > diff;\n\n    const visibleArea = Math.max(\n      this._monthScroller.itemHeight,\n      this._monthScroller.clientHeight - this._monthScroller.bufferOffset * 2,\n    );\n    const visibleItems = visibleArea / this._monthScroller.itemHeight;\n    const scrolledBelowViewport = this._monthScroller.position + visibleItems - 1 < diff;\n\n    if (scrolledAboveViewport) {\n      this._scrollToPosition(diff, animate);\n    } else if (scrolledBelowViewport) {\n      this._scrollToPosition(diff - visibleItems + 1, animate);\n    }\n  }\n\n  /**\n   * Calculates an offset to be added to the month scroll position\n   * when using sub-month scrolling, in order ensure that the week\n   * that the date is in is visible even for small scroll areas.\n   * As the month scroller uses a month as minimal scroll unit\n   * (a value of `1` equals one month), we can not exactly identify\n   * the position of a specific week. This is a best effort\n   * implementation based on manual testing.\n   * @param date the date for which to calculate the offset\n   * @returns {number} the offset\n   * @private\n   */\n  _calculateWeekScrollOffset(date) {\n    // Get first day of month\n    const temp = new Date(0, 0);\n    temp.setFullYear(date.getFullYear());\n    temp.setMonth(date.getMonth());\n    temp.setDate(1);\n    // Determine week (=row index) of date within the month\n    let week = 0;\n    while (temp.getDate() < date.getDate()) {\n      temp.setDate(temp.getDate() + 1);\n      if (temp.getDay() === this.i18n.firstDayOfWeek) {\n        week += 1;\n      }\n    }\n    // Calculate magic number that approximately keeps the week visible\n    return week / 6;\n  }\n\n  _initialPositionChanged(initialPosition) {\n    if (this._monthScroller && this._yearScroller) {\n      this._monthScroller.active = true;\n      this._yearScroller.active = true;\n    }\n\n    this.scrollToDate(initialPosition);\n  }\n\n  _repositionYearScroller() {\n    const monthPosition = this._monthScroller.position;\n    this._visibleMonthIndex = Math.floor(monthPosition);\n    this._yearScroller.position = (monthPosition + this._originDate.getMonth()) / 12;\n  }\n\n  _repositionMonthScroller() {\n    this._monthScroller.position = this._yearScroller.position * 12 - this._originDate.getMonth();\n    this._visibleMonthIndex = Math.floor(this._monthScroller.position);\n  }\n\n  _onMonthScroll() {\n    this._repositionYearScroller();\n    this._doIgnoreTaps();\n  }\n\n  _onYearScroll() {\n    this._repositionMonthScroller();\n    this._doIgnoreTaps();\n  }\n\n  _onYearScrollTouchStart() {\n    this._notTapping = false;\n    setTimeout(() => {\n      this._notTapping = true;\n    }, 300);\n\n    this._repositionMonthScroller();\n  }\n\n  _onMonthScrollTouchStart() {\n    this._repositionYearScroller();\n  }\n\n  _doIgnoreTaps() {\n    this._ignoreTaps = true;\n    this._debouncer = Debouncer.debounce(this._debouncer, timeOut.after(300), () => {\n      this._ignoreTaps = false;\n    });\n  }\n\n  _formatDisplayed(date, formatDate, label) {\n    if (date) {\n      return formatDate(extractDateParts(date));\n    }\n    return label;\n  }\n\n  _onTodayTap() {\n    const today = new Date();\n\n    if (Math.abs(this._monthScroller.position - this._differenceInMonths(today, this._originDate)) < 0.001) {\n      // Select today only if the month scroller is positioned approximately\n      // at the beginning of the current month\n      this._selectDate(today);\n      this._close();\n    } else {\n      this._scrollToCurrentMonth();\n    }\n  }\n\n  _scrollToCurrentMonth() {\n    if (this.focusedDate) {\n      this.focusedDate = new Date();\n    }\n\n    this.scrollToDate(new Date(), true);\n  }\n\n  _onYearTap(e) {\n    if (!this._ignoreTaps && !this._notTapping) {\n      const scrollDelta =\n        e.detail.y - (this._yearScroller.getBoundingClientRect().top + this._yearScroller.clientHeight / 2);\n      const yearDelta = scrollDelta / this._yearScroller.itemHeight;\n      this._scrollToPosition(this._monthScroller.position + yearDelta * 12, true);\n    }\n  }\n\n  _scrollToPosition(targetPosition, animate) {\n    if (this._targetPosition !== undefined) {\n      this._targetPosition = targetPosition;\n      return;\n    }\n\n    if (!animate) {\n      this._monthScroller.position = targetPosition;\n      this._targetPosition = undefined;\n      this._repositionYearScroller();\n      this.__tryFocusDate();\n      return;\n    }\n\n    this._targetPosition = targetPosition;\n\n    let revealResolve;\n    this._revealPromise = new Promise((resolve) => {\n      revealResolve = resolve;\n    });\n\n    // http://gizma.com/easing/\n    const easingFunction = (t, b, c, d) => {\n      t /= d / 2;\n      if (t < 1) {\n        return (c / 2) * t * t + b;\n      }\n      t -= 1;\n      return (-c / 2) * (t * (t - 2) - 1) + b;\n    };\n\n    let start = 0;\n    const initialPosition = this._monthScroller.position;\n\n    const smoothScroll = (timestamp) => {\n      if (!start) {\n        start = timestamp;\n      }\n\n      const currentTime = timestamp - start;\n\n      if (currentTime < this.scrollDuration) {\n        const currentPos = easingFunction(\n          currentTime,\n          initialPosition,\n          this._targetPosition - initialPosition,\n          this.scrollDuration,\n        );\n        this._monthScroller.position = currentPos;\n        window.requestAnimationFrame(smoothScroll);\n      } else {\n        this.dispatchEvent(\n          new CustomEvent('scroll-animation-finished', {\n            bubbles: true,\n            composed: true,\n            detail: {\n              position: this._targetPosition,\n              oldPosition: initialPosition,\n            },\n          }),\n        );\n\n        this._monthScroller.position = this._targetPosition;\n        this._targetPosition = undefined;\n\n        revealResolve();\n        this._revealPromise = undefined;\n      }\n\n      setTimeout(this._repositionYearScroller.bind(this), 1);\n    };\n\n    // Start the animation.\n    window.requestAnimationFrame(smoothScroll);\n  }\n\n  _limit(value, range) {\n    return Math.min(range.max, Math.max(range.min, value));\n  }\n\n  _handleTrack(e) {\n    // Check if horizontal movement threshold (dx) not exceeded or\n    // scrolling fast vertically (ddy).\n    if (Math.abs(e.detail.dx) < 10 || Math.abs(e.detail.ddy) > 10) {\n      return;\n    }\n\n    // If we're flinging quickly -> start animating already.\n    if (Math.abs(e.detail.ddx) > this._yearScrollerWidth / 3) {\n      this._toggleAnimateClass(true);\n    }\n\n    const newTranslateX = this._translateX + e.detail.ddx;\n    this._translateX = this._limit(newTranslateX, {\n      min: 0,\n      max: this._yearScrollerWidth,\n    });\n  }\n\n  _track(e) {\n    if (this._desktopMode) {\n      // No need to track for swipe gestures on desktop.\n      return;\n    }\n\n    switch (e.detail.state) {\n      case 'start':\n        this._toggleAnimateClass(false);\n        break;\n      case 'track':\n        this._handleTrack(e);\n        break;\n      case 'end':\n        this._toggleAnimateClass(true);\n        if (this._translateX >= this._yearScrollerWidth / 2) {\n          this._closeYearScroller();\n        } else {\n          this._openYearScroller();\n        }\n        break;\n      default:\n        break;\n    }\n  }\n\n  _toggleAnimateClass(enable) {\n    if (enable) {\n      this.classList.add('animate');\n    } else {\n      this.classList.remove('animate');\n    }\n  }\n\n  _toggleYearScroller() {\n    if (this._isYearScrollerVisible()) {\n      this._closeYearScroller();\n    } else {\n      this._openYearScroller();\n    }\n  }\n\n  _openYearScroller() {\n    this._translateX = 0;\n    this.setAttribute('years-visible', '');\n  }\n\n  _closeYearScroller() {\n    this.removeAttribute('years-visible');\n    this._translateX = this._yearScrollerWidth;\n  }\n\n  _isYearScrollerVisible() {\n    return this._translateX < this._yearScrollerWidth / 2;\n  }\n\n  _translateXChanged(x) {\n    if (!this._desktopMode) {\n      this._monthScroller.style.transform = `translateX(${x - this._yearScrollerWidth}px)`;\n      this._yearScroller.style.transform = `translateX(${x}px)`;\n    }\n  }\n\n  _yearAfterXMonths(months) {\n    return dateAfterXMonths(months).getFullYear();\n  }\n\n  _differenceInMonths(date1, date2) {\n    const months = (date1.getFullYear() - date2.getFullYear()) * 12;\n    return months - date2.getMonth() + date1.getMonth();\n  }\n\n  _clear() {\n    this._selectDate('');\n  }\n\n  _close() {\n    this.dispatchEvent(new CustomEvent('close', { bubbles: true, composed: true }));\n  }\n\n  _cancel() {\n    this.focusedDate = this.selectedDate;\n    this._close();\n  }\n\n  _preventDefault(e) {\n    e.preventDefault();\n  }\n\n  __toggleDate(date) {\n    if (dateEquals(date, this.selectedDate)) {\n      this._clear();\n      this.focusedDate = date;\n    } else {\n      this._selectDate(date);\n    }\n  }\n\n  __onMonthCalendarKeyDown(event) {\n    let handled = false;\n\n    switch (event.key) {\n      case 'ArrowDown':\n        this._moveFocusByDays(7);\n        handled = true;\n        break;\n      case 'ArrowUp':\n        this._moveFocusByDays(-7);\n        handled = true;\n        break;\n      case 'ArrowRight':\n        this._moveFocusByDays(this.__isRTL ? -1 : 1);\n        handled = true;\n        break;\n      case 'ArrowLeft':\n        this._moveFocusByDays(this.__isRTL ? 1 : -1);\n        handled = true;\n        break;\n      case 'Enter':\n        this._selectDate(this.focusedDate);\n        this._close();\n        handled = true;\n        break;\n      case ' ':\n        this.__toggleDate(this.focusedDate);\n        handled = true;\n        break;\n      case 'Home':\n        this._moveFocusInsideMonth(this.focusedDate, 'minDate');\n        handled = true;\n        break;\n      case 'End':\n        this._moveFocusInsideMonth(this.focusedDate, 'maxDate');\n        handled = true;\n        break;\n      case 'PageDown':\n        this._moveFocusByMonths(event.shiftKey ? 12 : 1);\n        handled = true;\n        break;\n      case 'PageUp':\n        this._moveFocusByMonths(event.shiftKey ? -12 : -1);\n        handled = true;\n        break;\n      case 'Tab':\n        this._onTabKeyDown(event, 'calendar');\n        break;\n      default:\n        break;\n    }\n\n    if (handled) {\n      event.preventDefault();\n      event.stopPropagation();\n    }\n  }\n\n  _onTabKeyDown(event, section) {\n    // Stop propagation to avoid focus-trap\n    // listener when used in a modal dialog.\n    event.stopPropagation();\n\n    switch (section) {\n      case 'calendar':\n        if (event.shiftKey) {\n          event.preventDefault();\n\n          if (this.hasAttribute('fullscreen')) {\n            // Trap focus in the overlay\n            this.focusCancel();\n          } else {\n            this.__focusInput();\n          }\n        }\n        break;\n      case 'today':\n        if (event.shiftKey) {\n          event.preventDefault();\n          this.focusDateElement();\n        }\n        break;\n      case 'cancel':\n        if (!event.shiftKey) {\n          event.preventDefault();\n\n          if (this.hasAttribute('fullscreen')) {\n            // Trap focus in the overlay\n            this.focusDateElement();\n          } else {\n            this.__focusInput();\n          }\n        }\n        break;\n      default:\n        break;\n    }\n  }\n\n  __onTodayButtonKeyDown(event) {\n    if (event.key === 'Tab') {\n      this._onTabKeyDown(event, 'today');\n    }\n  }\n\n  __onCancelButtonKeyDown(event) {\n    if (event.key === 'Tab') {\n      this._onTabKeyDown(event, 'cancel');\n    }\n  }\n\n  __focusInput() {\n    this.dispatchEvent(new CustomEvent('focus-input', { bubbles: true, composed: true }));\n  }\n\n  __tryFocusDate() {\n    const dateToFocus = this.__pendingDateFocus;\n    if (dateToFocus) {\n      // Check the date element with tabindex=\"0\"\n      const dateElement = this.focusableDateElement;\n\n      if (dateElement && dateEquals(dateElement.date, this.__pendingDateFocus)) {\n        delete this.__pendingDateFocus;\n        dateElement.focus();\n      }\n    }\n  }\n\n  async focusDate(date, keepMonth) {\n    const dateToFocus = date || this.selectedDate || this.initialPosition || new Date();\n    this.focusedDate = dateToFocus;\n    if (!keepMonth) {\n      this._focusedMonthDate = dateToFocus.getDate();\n    }\n    await this.focusDateElement(false);\n  }\n\n  async focusDateElement(reveal = true) {\n    this.__pendingDateFocus = this.focusedDate;\n\n    // Wait for `vaadin-month-calendar` elements to be rendered\n    if (!this.calendars.length) {\n      await new Promise((resolve) => {\n        afterNextRender(this, () => {\n          // Force dom-repeat elements to render\n          flush();\n          resolve();\n        });\n      });\n    }\n\n    // Reveal focused date unless it has been just set,\n    // which triggers `revealDate()` in the observer.\n    if (reveal) {\n      this.revealDate(this.focusedDate);\n    }\n\n    if (this._revealPromise) {\n      // Wait for focused date to be scrolled into view.\n      await this._revealPromise;\n    }\n\n    this.__tryFocusDate();\n  }\n\n  _focusClosestDate(focus) {\n    this.focusDate(getClosestDate(focus, [this.minDate, this.maxDate]));\n  }\n\n  _focusAllowedDate(dateToFocus, diff, keepMonth) {\n    if (this._dateAllowed(dateToFocus)) {\n      this.focusDate(dateToFocus, keepMonth);\n    } else if (this._dateAllowed(this.focusedDate)) {\n      // Move to min or max date\n      if (diff > 0) {\n        // Down, Right or Page Down key\n        this.focusDate(this.maxDate);\n      } else {\n        // Up, Left or Page Up key\n        this.focusDate(this.minDate);\n      }\n    } else {\n      // Move to closest allowed date\n      this._focusClosestDate(this.focusedDate);\n    }\n  }\n\n  _getDateDiff(months, days) {\n    const date = new Date(0, 0);\n    date.setFullYear(this.focusedDate.getFullYear());\n    date.setMonth(this.focusedDate.getMonth() + months);\n    if (days) {\n      date.setDate(this.focusedDate.getDate() + days);\n    }\n    return date;\n  }\n\n  _moveFocusByDays(days) {\n    const dateToFocus = this._getDateDiff(0, days);\n\n    this._focusAllowedDate(dateToFocus, days, false);\n  }\n\n  _moveFocusByMonths(months) {\n    const dateToFocus = this._getDateDiff(months);\n    const targetMonth = dateToFocus.getMonth();\n\n    if (!this._focusedMonthDate) {\n      this._focusedMonthDate = this.focusedDate.getDate();\n    }\n\n    dateToFocus.setDate(this._focusedMonthDate);\n\n    if (dateToFocus.getMonth() !== targetMonth) {\n      dateToFocus.setDate(0);\n    }\n\n    this._focusAllowedDate(dateToFocus, months, true);\n  }\n\n  _moveFocusInsideMonth(focusedDate, property) {\n    const dateToFocus = new Date(0, 0);\n    dateToFocus.setFullYear(focusedDate.getFullYear());\n\n    if (property === 'minDate') {\n      dateToFocus.setMonth(focusedDate.getMonth());\n      dateToFocus.setDate(1);\n    } else {\n      dateToFocus.setMonth(focusedDate.getMonth() + 1);\n      dateToFocus.setDate(0);\n    }\n\n    if (this._dateAllowed(dateToFocus)) {\n      this.focusDate(dateToFocus);\n    } else if (this._dateAllowed(focusedDate)) {\n      // Move to minDate or maxDate\n      this.focusDate(this[property]);\n    } else {\n      // Move to closest allowed date\n      this._focusClosestDate(focusedDate);\n    }\n  }\n\n  _dateAllowed(date, min = this.minDate, max = this.maxDate) {\n    return (!min || date >= min) && (!max || date <= max);\n  }\n\n  _isTodayAllowed(min, max) {\n    const today = new Date();\n    const todayMidnight = new Date(0, 0);\n    todayMidnight.setFullYear(today.getFullYear());\n    todayMidnight.setMonth(today.getMonth());\n    todayMidnight.setDate(today.getDate());\n    return this._dateAllowed(todayMidnight, min, max);\n  }\n}\n\ncustomElements.define(DatePickerOverlayContent.is, DatePickerOverlayContent);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\nimport { FocusMixin } from './focus-mixin.js';\nimport { TabindexMixin } from './tabindex-mixin.js';\n\n/**\n * A mixin to forward focus to an element in the light DOM.\n *\n * @polymerMixin\n * @mixes FocusMixin\n * @mixes TabindexMixin\n */\nexport const DelegateFocusMixin = dedupingMixin(\n  (superclass) =>\n    class DelegateFocusMixinClass extends FocusMixin(TabindexMixin(superclass)) {\n      static get properties() {\n        return {\n          /**\n           * Specify that this control should have input focus when the page loads.\n           */\n          autofocus: {\n            type: Boolean,\n          },\n\n          /**\n           * A reference to the focusable element controlled by the mixin.\n           * It can be an input, textarea, button or any element with tabindex > -1.\n           *\n           * Any component implementing this mixin is expected to provide it\n           * by using `this._setFocusElement(input)` Polymer API.\n           *\n           * Toggling `tabindex` attribute on the host element propagates its value to `focusElement`.\n           *\n           * @protected\n           * @type {!HTMLElement}\n           */\n          focusElement: {\n            type: Object,\n            readOnly: true,\n            observer: '_focusElementChanged',\n          },\n\n          /**\n           * Override the property from `TabIndexMixin`\n           * to ensure the `tabindex` attribute of the focus element\n           * will be restored to `0` after re-enabling the element.\n           *\n           * @protected\n           * @override\n           */\n          _lastTabIndex: {\n            value: 0,\n          },\n        };\n      }\n\n      constructor() {\n        super();\n\n        this._boundOnBlur = this._onBlur.bind(this);\n        this._boundOnFocus = this._onFocus.bind(this);\n      }\n\n      /** @protected */\n      ready() {\n        super.ready();\n\n        if (this.autofocus && !this.disabled) {\n          requestAnimationFrame(() => {\n            this.focus();\n            this.setAttribute('focus-ring', '');\n          });\n        }\n      }\n\n      /**\n       * @protected\n       * @override\n       */\n      focus() {\n        if (!this.focusElement || this.disabled) {\n          return;\n        }\n\n        this.focusElement.focus();\n        this._setFocused(true);\n      }\n\n      /**\n       * @protected\n       * @override\n       */\n      blur() {\n        if (!this.focusElement) {\n          return;\n        }\n        this.focusElement.blur();\n        this._setFocused(false);\n      }\n\n      /**\n       * @protected\n       * @override\n       */\n      click() {\n        if (this.focusElement && !this.disabled) {\n          this.focusElement.click();\n        }\n      }\n\n      /** @protected */\n      _focusElementChanged(element, oldElement) {\n        if (element) {\n          element.disabled = this.disabled;\n          this._addFocusListeners(element);\n          this.__forwardTabIndex(this.tabindex);\n        } else if (oldElement) {\n          this._removeFocusListeners(oldElement);\n        }\n      }\n\n      /**\n       * @param {HTMLElement} element\n       * @protected\n       */\n      _addFocusListeners(element) {\n        element.addEventListener('blur', this._boundOnBlur);\n        element.addEventListener('focus', this._boundOnFocus);\n      }\n\n      /**\n       * @param {HTMLElement} element\n       * @protected\n       */\n      _removeFocusListeners(element) {\n        element.removeEventListener('blur', this._boundOnBlur);\n        element.removeEventListener('focus', this._boundOnFocus);\n      }\n\n      /**\n       * Focus event does not bubble, so we dispatch it manually\n       * on the host element to support adding focus listeners\n       * when the focusable element is placed in light DOM.\n       * @param {FocusEvent} event\n       * @protected\n       */\n      _onFocus(event) {\n        event.stopPropagation();\n        this.dispatchEvent(new Event('focus'));\n      }\n\n      /**\n       * Blur event does not bubble, so we dispatch it manually\n       * on the host element to support adding blur listeners\n       * when the focusable element is placed in light DOM.\n       * @param {FocusEvent} event\n       * @protected\n       */\n      _onBlur(event) {\n        event.stopPropagation();\n        this.dispatchEvent(new Event('blur'));\n      }\n\n      /**\n       * @param {FocusEvent} event\n       * @return {boolean}\n       * @protected\n       * @override\n       */\n      _shouldSetFocus(event) {\n        return event.target === this.focusElement;\n      }\n\n      /**\n       * @param {FocusEvent} event\n       * @return {boolean}\n       * @protected\n       * @override\n       */\n      _shouldRemoveFocus(event) {\n        return event.target === this.focusElement;\n      }\n\n      /**\n       * @param {boolean} disabled\n       * @param {boolean} oldDisabled\n       * @protected\n       * @override\n       */\n      _disabledChanged(disabled, oldDisabled) {\n        super._disabledChanged(disabled, oldDisabled);\n\n        if (this.focusElement) {\n          this.focusElement.disabled = disabled;\n        }\n\n        if (disabled) {\n          this.blur();\n        }\n      }\n\n      /**\n       * Override an observer from `TabindexMixin`.\n       * Do not call super to remove tabindex attribute\n       * from the host after it has been forwarded.\n       * @param {string} tabindex\n       * @protected\n       * @override\n       */\n      _tabindexChanged(tabindex) {\n        this.__forwardTabIndex(tabindex);\n      }\n\n      /** @private */\n      __forwardTabIndex(tabindex) {\n        if (tabindex !== undefined && this.focusElement) {\n          this.focusElement.tabIndex = tabindex;\n\n          // Preserve tabindex=\"-1\" on the host element\n          if (tabindex !== -1) {\n            this.tabindex = undefined;\n          }\n        }\n\n        if (this.disabled && tabindex) {\n          // If tabindex attribute was changed while component was disabled\n          if (tabindex !== -1) {\n            this._lastTabIndex = tabindex;\n          }\n          this.tabindex = undefined;\n        }\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\n\n/**\n * A mixin to store the reference to an input element\n * and add input and change event listeners to it.\n *\n * @polymerMixin\n */\nexport const InputMixin = dedupingMixin(\n  (superclass) =>\n    class InputMixinClass extends superclass {\n      static get properties() {\n        return {\n          /**\n           * A reference to the input element controlled by the mixin.\n           * Any component implementing this mixin is expected to provide it\n           * by using `this._setInputElement(input)` Polymer API.\n           *\n           * A typical case is using `InputController` that does this automatically.\n           * However, the input element does not have to always be native <input>:\n           * as an example, <vaadin-combo-box-light> accepts other components.\n           *\n           * @protected\n           * @type {!HTMLElement}\n           */\n          inputElement: {\n            type: Object,\n            readOnly: true,\n            observer: '_inputElementChanged',\n          },\n\n          /**\n           * String used to define input type.\n           * @protected\n           */\n          type: {\n            type: String,\n            readOnly: true,\n          },\n\n          /**\n           * The value of the field.\n           */\n          value: {\n            type: String,\n            value: '',\n            observer: '_valueChanged',\n            notify: true,\n          },\n\n          /**\n           * Whether the input element has a non-empty value.\n           *\n           * @protected\n           */\n          _hasInputValue: {\n            type: Boolean,\n            value: false,\n            observer: '_hasInputValueChanged',\n          },\n        };\n      }\n\n      constructor() {\n        super();\n\n        this._boundOnInput = this.__onInput.bind(this);\n        this._boundOnChange = this._onChange.bind(this);\n      }\n\n      /**\n       * Indicates whether the value is different from the default one.\n       * Override if the `value` property has a type other than `string`.\n       *\n       * @protected\n       */\n      get _hasValue() {\n        return this.value != null && this.value !== '';\n      }\n\n      /**\n       * A property for accessing the input element's value.\n       *\n       * Override this getter if the property is different from the default `value` one.\n       *\n       * @protected\n       * @return {string}\n       */\n      get _inputElementValueProperty() {\n        return 'value';\n      }\n\n      /**\n       * The input element's value.\n       *\n       * @protected\n       * @return {string}\n       */\n      get _inputElementValue() {\n        return this.inputElement ? this.inputElement[this._inputElementValueProperty] : undefined;\n      }\n\n      /**\n       * The input element's value.\n       *\n       * @protected\n       */\n      set _inputElementValue(value) {\n        if (this.inputElement) {\n          this.inputElement[this._inputElementValueProperty] = value;\n        }\n      }\n\n      /**\n       * Clear the value of the field.\n       */\n      clear() {\n        this._hasInputValue = false;\n\n        this.value = '';\n\n        // Clear the input immediately without waiting for the observer.\n        // Otherwise, when using Lit, the old value would be restored.\n        this._inputElementValue = '';\n      }\n\n      /**\n       * Add event listeners to the input element instance.\n       * Override this method to add custom listeners.\n       * @param {!HTMLElement} input\n       * @protected\n       */\n      _addInputListeners(input) {\n        input.addEventListener('input', this._boundOnInput);\n        input.addEventListener('change', this._boundOnChange);\n      }\n\n      /**\n       * Remove event listeners from the input element instance.\n       * @param {!HTMLElement} input\n       * @protected\n       */\n      _removeInputListeners(input) {\n        input.removeEventListener('input', this._boundOnInput);\n        input.removeEventListener('change', this._boundOnChange);\n      }\n\n      /**\n       * A method to forward the value property set on the field\n       * programmatically back to the input element value.\n       * Override this method to perform additional checks,\n       * for example to skip this in certain conditions.\n       * @param {string} value\n       * @protected\n       */\n      _forwardInputValue(value) {\n        // Value might be set before an input element is initialized.\n        // This case should be handled separately by a component that\n        // implements this mixin, for example in `connectedCallback`.\n        if (!this.inputElement) {\n          return;\n        }\n\n        this._inputElementValue = value != null ? value : '';\n      }\n\n      /**\n       * @param {HTMLElement | undefined} input\n       * @param {HTMLElement | undefined} oldInput\n       * @protected\n       */\n      _inputElementChanged(input, oldInput) {\n        if (input) {\n          this._addInputListeners(input);\n        } else if (oldInput) {\n          this._removeInputListeners(oldInput);\n        }\n      }\n\n      /**\n       * Observer to notify about the change of private property.\n       *\n       * @private\n       */\n      _hasInputValueChanged(hasValue, oldHasValue) {\n        if (hasValue || oldHasValue) {\n          this.dispatchEvent(new CustomEvent('has-input-value-changed'));\n        }\n      }\n\n      /**\n       * An input event listener used to update `_hasInputValue` property.\n       * Do not override this method.\n       *\n       * @param {Event} event\n       * @private\n       */\n      __onInput(event) {\n        this._setHasInputValue(event);\n        this._onInput(event);\n      }\n\n      /**\n       * An input event listener used to update the field value.\n       *\n       * @param {Event} event\n       * @protected\n       */\n      _onInput(event) {\n        // In the case a custom web component is passed as `inputElement`,\n        // the actual native input element, on which the event occurred,\n        // can be inside shadow trees.\n        const target = event.composedPath()[0];\n        // Ignore fake input events e.g. used by clear button.\n        this.__userInput = event.isTrusted;\n        this.value = target.value;\n        this.__userInput = false;\n      }\n\n      /**\n       * A change event listener.\n       * Override this method with an actual implementation.\n       * @param {Event} _event\n       * @protected\n       */\n      _onChange(_event) {}\n\n      /**\n       * Toggle the has-value attribute based on the value property.\n       *\n       * @param {boolean} hasValue\n       * @protected\n       */\n      _toggleHasValue(hasValue) {\n        this.toggleAttribute('has-value', hasValue);\n      }\n\n      /**\n       * Observer called when a value property changes.\n       * @param {string | undefined} newVal\n       * @param {string | undefined} oldVal\n       * @protected\n       */\n      _valueChanged(newVal, oldVal) {\n        this._toggleHasValue(this._hasValue);\n\n        // Setting initial value to empty string, do nothing.\n        if (newVal === '' && oldVal === undefined) {\n          return;\n        }\n\n        // Value is set by the user, no need to sync it back to input.\n        if (this.__userInput) {\n          return;\n        }\n\n        // Setting a value programmatically, sync it to input element.\n        this._forwardInputValue(newVal);\n      }\n\n      /**\n       * Sets the `_hasInputValue` property based on the `input` event.\n       *\n       * @param {InputEvent} event\n       * @protected\n       */\n      _setHasInputValue(event) {\n        // In the case a custom web component is passed as `inputElement`,\n        // the actual native input element, on which the event occurred,\n        // can be inside shadow trees.\n        const target = event.composedPath()[0];\n        this._hasInputValue = target.value.length > 0;\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { KeyboardMixin } from '@vaadin/a11y-base/src/keyboard-mixin.js';\nimport { isTouch } from '@vaadin/component-base/src/browser-utils.js';\nimport { InputMixin } from './input-mixin.js';\n\n/**\n * A mixin that manages the clear button.\n *\n * @polymerMixin\n * @mixes InputMixin\n * @mixes KeyboardMixin\n */\nexport const ClearButtonMixin = (superclass) =>\n  class ClearButtonMixinClass extends InputMixin(KeyboardMixin(superclass)) {\n    static get properties() {\n      return {\n        /**\n         * Set to true to display the clear icon which clears the input.\n         *\n         * It is up to the component to choose where to place the clear icon:\n         * in the Shadow DOM or in the light DOM. In any way, a reference to\n         * the clear icon element should be provided via the `clearElement` getter.\n         *\n         * @attr {boolean} clear-button-visible\n         */\n        clearButtonVisible: {\n          type: Boolean,\n          reflectToAttribute: true,\n          value: false,\n        },\n      };\n    }\n\n    /**\n     * Any element extending this mixin is required to implement this getter.\n     * It returns the reference to the clear button element.\n     *\n     * @protected\n     * @return {Element | null | undefined}\n     */\n    get clearElement() {\n      console.warn(`Please implement the 'clearElement' property in <${this.localName}>`);\n      return null;\n    }\n\n    /** @protected */\n    ready() {\n      super.ready();\n\n      if (this.clearElement) {\n        this.clearElement.addEventListener('mousedown', (event) => this._onClearButtonMouseDown(event));\n        this.clearElement.addEventListener('click', (event) => this._onClearButtonClick(event));\n      }\n    }\n\n    /**\n     * @param {Event} event\n     * @protected\n     */\n    _onClearButtonClick(event) {\n      event.preventDefault();\n      this._onClearAction();\n    }\n\n    /**\n     * @param {MouseEvent} event\n     * @protected\n     */\n    _onClearButtonMouseDown(event) {\n      event.preventDefault();\n      if (!isTouch) {\n        this.inputElement.focus();\n      }\n    }\n\n    /**\n     * Override an event listener inherited from `KeydownMixin` to clear on Esc.\n     * Components that extend this mixin can prevent this behavior by overriding\n     * this method without calling `super._onEscape` to provide custom logic.\n     *\n     * @param {KeyboardEvent} event\n     * @protected\n     * @override\n     */\n    _onEscape(event) {\n      super._onEscape(event);\n\n      if (this.clearButtonVisible && !!this.value) {\n        event.stopPropagation();\n        this._onClearAction();\n      }\n    }\n\n    /**\n     * Clears the value and dispatches `input` and `change` events\n     * on the input element. This method should be called\n     * when the clear action originates from the user.\n     *\n     * @protected\n     */\n    _onClearAction() {\n      this.clear();\n      // Note, according to the HTML spec, the native change event isn't composed\n      // while the input event is composed.\n      this.inputElement.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n      this.inputElement.dispatchEvent(new Event('change', { bubbles: true }));\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport {\n  addValueToAttribute,\n  deserializeAttributeValue,\n  removeValueFromAttribute,\n  serializeAttributeValue,\n} from '@vaadin/component-base/src/dom-utils.js';\n\nconst attributeToTargets = new Map();\n\n/**\n * Gets or creates a Set with the stored values for each element controlled by this helper\n *\n * @param {string} attr the attribute name used as key in the map\n *\n * @returns {WeakMap<HTMLElement, Set<string>} a weak map with the stored values for the elements being controlled by the helper\n */\nfunction getAttrMap(attr) {\n  if (!attributeToTargets.has(attr)) {\n    attributeToTargets.set(attr, new WeakMap());\n  }\n  return attributeToTargets.get(attr);\n}\n\n/**\n * Cleans the values set on the attribute to the given element.\n * It also stores the current values in the map, if `storeValue` is `true`.\n *\n * @param {HTMLElement} target\n * @param {string} attr the attribute to be cleared\n * @param {boolean} storeValue whether or not the current value of the attribute should be stored on the map\n * @returns\n */\nfunction cleanAriaIDReference(target, attr) {\n  if (!target) {\n    return;\n  }\n\n  target.removeAttribute(attr);\n}\n\n/**\n * Storing values of the accessible attributes in a Set inside of the WeakMap.\n *\n * @param {HTMLElement} target\n * @param {string} attr the attribute to be stored\n */\nfunction storeAriaIDReference(target, attr) {\n  if (!target || !attr) {\n    return;\n  }\n  const attributeMap = getAttrMap(attr);\n  if (attributeMap.has(target)) {\n    return;\n  }\n  const values = deserializeAttributeValue(target.getAttribute(attr));\n  attributeMap.set(target, new Set(values));\n}\n\n/**\n * Restores the generated values of the attribute to the given element.\n *\n * @param {HTMLElement} target\n * @param {string} attr\n */\nexport function restoreGeneratedAriaIDReference(target, attr) {\n  if (!target || !attr) {\n    return;\n  }\n  const attributeMap = getAttrMap(attr);\n  const values = attributeMap.get(target);\n  if (!values || values.size === 0) {\n    target.removeAttribute(attr);\n  } else {\n    addValueToAttribute(target, attr, serializeAttributeValue(values));\n  }\n  attributeMap.delete(target);\n}\n\n/**\n * Sets a new ID reference for a target element and an ARIA attribute.\n *\n * @typedef {Object} AriaIdReferenceConfig\n * @property {string | null | undefined} newId\n * @property {string | null | undefined} oldId\n * @property {boolean | null | undefined} fromUser\n * @param {HTMLElement} target\n * @param {string} attr\n * @param {AriaIdReferenceConfig | null | undefined} config\n * @param config.newId The new ARIA ID reference to set. If `null`, the attribute is removed,\n * and `config.fromUser` is true, any stored values are restored. If there are stored values\n * and `config.fromUser` is `false`, then `config.newId` is added to the stored values set.\n * @param config.oldId The ARIA ID reference to be removed from the attribute. If there are\n * stored values and `config.fromUser` is `false`, then `config.oldId` is removed from the\n * stored values set.\n * @param config.fromUser Indicates whether the function is called by the user or internally.\n * When `config.fromUser` is called with `true` for the first time, the function will clear\n * and store the attribute value for the given element.\n */\nexport function setAriaIDReference(target, attr, config = { newId: null, oldId: null, fromUser: false }) {\n  if (!target || !attr) {\n    return;\n  }\n\n  const { newId, oldId, fromUser } = config;\n\n  const attributeMap = getAttrMap(attr);\n  const storedValues = attributeMap.get(target);\n\n  if (!fromUser && !!storedValues) {\n    // If there's any stored values, it means the attribute is being handled by the user\n    // Replace the \"oldId\" with \"newId\" on the stored values set and leave\n    oldId && storedValues.delete(oldId);\n    newId && storedValues.add(newId);\n    return;\n  }\n\n  if (fromUser) {\n    if (!storedValues) {\n      // If it's called from user and there's no stored values for the attribute,\n      // then store the current value\n      storeAriaIDReference(target, attr);\n    } else if (!newId) {\n      // If called from user with newId == null, it means the attribute will no longer\n      // be in control of the user and the stored values should be restored\n      // Removing the entry on the map for this target\n      attributeMap.delete(target);\n    }\n\n    // If it's from user, then clear the attribute value before setting newId\n    cleanAriaIDReference(target, attr);\n  }\n\n  removeValueFromAttribute(target, attr, oldId);\n\n  const attributeValue = !newId ? serializeAttributeValue(storedValues) : newId;\n  if (attributeValue) {\n    addValueToAttribute(target, attr, attributeValue);\n  }\n}\n\n/**\n * Removes the {@link attr | attribute} value of the given {@link target} element.\n * It also stores the current value, if no stored values are present.\n *\n * @param {HTMLElement} target\n * @param {string} attr\n */\nexport function removeAriaIDReference(target, attr) {\n  storeAriaIDReference(target, attr);\n  cleanAriaIDReference(target, attr);\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport {\n  removeAriaIDReference,\n  restoreGeneratedAriaIDReference,\n  setAriaIDReference,\n} from '@vaadin/a11y-base/src/aria-id-reference.js';\n\n/**\n * A controller for managing ARIA attributes for a field element:\n * either the component itself or slotted `<input>` element.\n */\nexport class FieldAriaController {\n  constructor(host) {\n    this.host = host;\n    this.__required = false;\n  }\n\n  /**\n   * Sets a target element to which ARIA attributes are added.\n   *\n   * @param {HTMLElement} target\n   */\n  setTarget(target) {\n    this.__target = target;\n    this.__setAriaRequiredAttribute(this.__required);\n    // We need to make sure that value in __labelId is stored\n    this.__setLabelIdToAriaAttribute(this.__labelId, this.__labelId);\n    if (this.__labelIdFromUser != null) {\n      this.__setLabelIdToAriaAttribute(this.__labelIdFromUser, this.__labelIdFromUser, true);\n    }\n    this.__setErrorIdToAriaAttribute(this.__errorId);\n    this.__setHelperIdToAriaAttribute(this.__helperId);\n    this.setAriaLabel(this.__label);\n  }\n\n  /**\n   * Toggles the `aria-required` attribute on the target element\n   * if the target is the host component (e.g. a field group).\n   * Otherwise, it does nothing.\n   *\n   * @param {boolean} required\n   */\n  setRequired(required) {\n    this.__setAriaRequiredAttribute(required);\n    this.__required = required;\n  }\n\n  /**\n   * Defines the `aria-label` attribute of the target element.\n   *\n   * To remove the attribute, pass `null` as `label`.\n   *\n   * @param {string | null | undefined} label\n   */\n  setAriaLabel(label) {\n    this.__setAriaLabelToAttribute(label);\n    this.__label = label;\n  }\n\n  /**\n   * Links the target element with a slotted label element\n   * via the target's attribute `aria-labelledby`.\n   *\n   * To unlink the previous slotted label element, pass `null` as `labelId`.\n   *\n   * @param {string | null} labelId\n   */\n  setLabelId(labelId, fromUser = false) {\n    const oldLabelId = fromUser ? this.__labelIdFromUser : this.__labelId;\n    this.__setLabelIdToAriaAttribute(labelId, oldLabelId, fromUser);\n    if (fromUser) {\n      this.__labelIdFromUser = labelId;\n    } else {\n      this.__labelId = labelId;\n    }\n  }\n\n  /**\n   * Links the target element with a slotted error element via the target's attribute:\n   * - `aria-labelledby` if the target is the host component (e.g a field group).\n   * - `aria-describedby` otherwise.\n   *\n   * To unlink the previous slotted error element, pass `null` as `errorId`.\n   *\n   * @param {string | null} errorId\n   */\n  setErrorId(errorId) {\n    this.__setErrorIdToAriaAttribute(errorId, this.__errorId);\n    this.__errorId = errorId;\n  }\n\n  /**\n   * Links the target element with a slotted helper element via the target's attribute:\n   * - `aria-labelledby` if the target is the host component (e.g a field group).\n   * - `aria-describedby` otherwise.\n   *\n   * To unlink the previous slotted helper element, pass `null` as `helperId`.\n   *\n   * @param {string | null} helperId\n   */\n  setHelperId(helperId) {\n    this.__setHelperIdToAriaAttribute(helperId, this.__helperId);\n    this.__helperId = helperId;\n  }\n\n  /**\n   * @param {string | null | undefined} label\n   * @private\n   * */\n  __setAriaLabelToAttribute(label) {\n    if (!this.__target) {\n      return;\n    }\n    if (label) {\n      removeAriaIDReference(this.__target, 'aria-labelledby');\n      this.__target.setAttribute('aria-label', label);\n    } else if (this.__label) {\n      restoreGeneratedAriaIDReference(this.__target, 'aria-labelledby');\n      this.__target.removeAttribute('aria-label');\n    }\n  }\n\n  /**\n   * @param {string | null | undefined} labelId\n   * @param {string | null | undefined} oldLabelId\n   * @param {boolean | null | undefined} fromUser\n   * @private\n   */\n  __setLabelIdToAriaAttribute(labelId, oldLabelId, fromUser) {\n    setAriaIDReference(this.__target, 'aria-labelledby', { newId: labelId, oldId: oldLabelId, fromUser });\n  }\n\n  /**\n   * @param {string | null | undefined} errorId\n   * @param {string | null | undefined} oldErrorId\n   * @private\n   */\n  __setErrorIdToAriaAttribute(errorId, oldErrorId) {\n    setAriaIDReference(this.__target, 'aria-describedby', { newId: errorId, oldId: oldErrorId, fromUser: false });\n  }\n\n  /**\n   * @param {string | null | undefined} helperId\n   * @param {string | null | undefined} oldHelperId\n   * @private\n   */\n  __setHelperIdToAriaAttribute(helperId, oldHelperId) {\n    setAriaIDReference(this.__target, 'aria-describedby', { newId: helperId, oldId: oldHelperId, fromUser: false });\n  }\n\n  /**\n   * @param {boolean} required\n   * @private\n   */\n  __setAriaRequiredAttribute(required) {\n    if (!this.__target) {\n      return;\n    }\n\n    if (['input', 'textarea'].includes(this.__target.localName)) {\n      // Native <input> or <textarea>, required is enough\n      return;\n    }\n\n    if (required) {\n      this.__target.setAttribute('aria-required', 'true');\n    } else {\n      this.__target.removeAttribute('aria-required');\n    }\n  }\n}\n","/**\n * @license\n * Copyright (c) 2022 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { SlotController } from './slot-controller.js';\n\n/**\n * A controller that observes slotted element mutations, especially ID attribute\n * and the text content, and fires an event to notify host element about those.\n */\nexport class SlotChildObserveController extends SlotController {\n  constructor(host, slot, tagName, config = {}) {\n    super(host, slot, tagName, { ...config, useUniqueId: true });\n  }\n\n  /**\n   * Override to initialize the newly added custom node.\n   *\n   * @param {Node} node\n   * @protected\n   * @override\n   */\n  initCustomNode(node) {\n    this.__updateNodeId(node);\n    this.__notifyChange(node);\n  }\n\n  /**\n   * Override to notify the controller host about removal of\n   * the custom node, and to apply the default one if needed.\n   *\n   * @param {Node} _node\n   * @protected\n   * @override\n   */\n  teardownNode(_node) {\n    const node = this.getSlotChild();\n\n    // Custom node is added to the slot\n    if (node && node !== this.defaultNode) {\n      this.__notifyChange(node);\n    } else {\n      this.restoreDefaultNode();\n      this.updateDefaultNode(this.node);\n    }\n  }\n\n  /**\n   * Override method inherited from `SlotMixin`\n   * to set ID attribute on the default node.\n   *\n   * @return {Node}\n   * @protected\n   * @override\n   */\n  attachDefaultNode() {\n    const node = super.attachDefaultNode();\n\n    if (node) {\n      this.__updateNodeId(node);\n    }\n\n    return node;\n  }\n\n  /**\n   * Override to restore default node when a custom one is removed.\n   *\n   * @protected\n   */\n  restoreDefaultNode() {\n    // To be implemented\n  }\n\n  /**\n   * Override to update default node text on property change.\n   *\n   * @param {Node} node\n   * @protected\n   */\n  updateDefaultNode(node) {\n    this.__notifyChange(node);\n  }\n\n  /**\n   * Setup the mutation observer on the node to update ID and notify host.\n   * Node doesn't get observed automatically until this method is called.\n   *\n   * @param {Node} node\n   * @protected\n   */\n  observeNode(node) {\n    // Stop observing the previous node, if any.\n    if (this.__nodeObserver) {\n      this.__nodeObserver.disconnect();\n    }\n\n    this.__nodeObserver = new MutationObserver((mutations) => {\n      mutations.forEach((mutation) => {\n        const target = mutation.target;\n\n        // Ensure the mutation target is the currently connected node\n        // to ignore async mutations dispatched for removed element.\n        const isCurrentNodeMutation = target === this.node;\n\n        if (mutation.type === 'attributes') {\n          // We use attributeFilter to only observe ID mutation,\n          // no need to check for attribute name separately.\n          if (isCurrentNodeMutation) {\n            this.__updateNodeId(target);\n          }\n        } else if (isCurrentNodeMutation || target.parentElement === this.node) {\n          // Node text content has changed.\n          this.__notifyChange(this.node);\n        }\n      });\n    });\n\n    // Observe changes to node ID attribute, text content and children.\n    this.__nodeObserver.observe(node, {\n      attributes: true,\n      attributeFilter: ['id'],\n      childList: true,\n      subtree: true,\n      characterData: true,\n    });\n  }\n\n  /**\n   * Returns true if a node is an HTML element with children,\n   * or is a defined custom element, or has non-empty text.\n   *\n   * @param {Node} node\n   * @return {boolean}\n   * @private\n   */\n  __hasContent(node) {\n    if (!node) {\n      return false;\n    }\n\n    return (\n      (node.nodeType === Node.ELEMENT_NODE && (customElements.get(node.localName) || node.children.length > 0)) ||\n      (node.textContent && node.textContent.trim() !== '')\n    );\n  }\n\n  /**\n   * Fire an event to notify the controller host about node changes.\n   *\n   * @param {Node} node\n   * @private\n   */\n  __notifyChange(node) {\n    this.dispatchEvent(\n      new CustomEvent('slot-content-changed', {\n        detail: { hasContent: this.__hasContent(node), node },\n      }),\n    );\n  }\n\n  /**\n   * Set default ID on the node in case it is an HTML element.\n   *\n   * @param {Node} node\n   * @private\n   */\n  __updateNodeId(node) {\n    // When in multiple mode, only set ID attribute on the element in default slot.\n    const isFirstNode = !this.nodes || node === this.nodes[0];\n    if (node.nodeType === Node.ELEMENT_NODE && (!this.multiple || isFirstNode) && !node.id) {\n      node.id = this.defaultId;\n    }\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { SlotChildObserveController } from '@vaadin/component-base/src/slot-child-observe-controller.js';\n\n/**\n * A controller that manages the error message node content.\n */\nexport class ErrorController extends SlotChildObserveController {\n  constructor(host) {\n    super(host, 'error-message', 'div');\n  }\n\n  /**\n   * Set the error message element text content.\n   *\n   * @param {string} errorMessage\n   */\n  setErrorMessage(errorMessage) {\n    this.errorMessage = errorMessage;\n\n    this.updateDefaultNode(this.node);\n  }\n\n  /**\n   * Set invalid state for detecting whether to show error message.\n   *\n   * @param {boolean} invalid\n   */\n  setInvalid(invalid) {\n    this.invalid = invalid;\n\n    this.updateDefaultNode(this.node);\n  }\n\n  /**\n   * Override method inherited from `SlotController` to not run\n   * initializer on the custom slotted node unnecessarily.\n   *\n   * @param {Node} node\n   * @protected\n   * @override\n   */\n  initAddedNode(node) {\n    if (node !== this.defaultNode) {\n      // There is no need to run `initNode`.\n      this.initCustomNode(node);\n    }\n  }\n\n  /**\n   * Override to initialize the newly added default error message.\n   *\n   * @param {Node} errorNode\n   * @protected\n   * @override\n   */\n  initNode(errorNode) {\n    this.updateDefaultNode(errorNode);\n  }\n\n  /**\n   * Override to initialize the newly added custom error message.\n   *\n   * @param {Node} errorNode\n   * @protected\n   * @override\n   */\n  initCustomNode(errorNode) {\n    // Save the custom error message content on the host.\n    if (errorNode.textContent && !this.errorMessage) {\n      this.errorMessage = errorNode.textContent.trim();\n    }\n\n    // Notify the host about custom node.\n    super.initCustomNode(errorNode);\n  }\n\n  /**\n   * Override method inherited from `SlotChildObserveController`\n   * to restore the default error message element.\n   *\n   * @protected\n   * @override\n   */\n  restoreDefaultNode() {\n    this.attachDefaultNode();\n  }\n\n  /**\n   * Override method inherited from `SlotChildObserveController`\n   * to update the error message text and hidden state.\n   *\n   * Note: unlike with other controllers, this method is\n   * called for both default and custom error message.\n   *\n   * @param {Node | undefined} node\n   * @protected\n   * @override\n   */\n  updateDefaultNode(errorNode) {\n    const { errorMessage, invalid } = this;\n    const hasError = Boolean(invalid && errorMessage && errorMessage.trim() !== '');\n\n    if (errorNode) {\n      errorNode.textContent = hasError ? errorMessage : '';\n      errorNode.hidden = !hasError;\n\n      // Role alert will make the error message announce immediately\n      // as the field becomes invalid\n      if (hasError) {\n        errorNode.setAttribute('role', 'alert');\n      } else {\n        errorNode.removeAttribute('role');\n      }\n    }\n\n    // Notify the host after update.\n    super.updateDefaultNode(errorNode);\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { SlotChildObserveController } from '@vaadin/component-base/src/slot-child-observe-controller.js';\n\n/**\n * A controller that manages the helper node content.\n */\nexport class HelperController extends SlotChildObserveController {\n  constructor(host) {\n    // Do not provide tag name, as we create helper lazily.\n    super(host, 'helper', null);\n  }\n\n  /**\n   * Set helper text based on corresponding host property.\n   *\n   * @param {string} helperText\n   */\n  setHelperText(helperText) {\n    this.helperText = helperText;\n\n    // Restore the default helper, if needed.\n    const helperNode = this.getSlotChild();\n    if (!helperNode) {\n      this.restoreDefaultNode();\n    }\n\n    // When default helper is used, update it.\n    if (this.node === this.defaultNode) {\n      this.updateDefaultNode(this.node);\n    }\n  }\n\n  /**\n   * Override method inherited from `SlotChildObserveController`\n   * to create the default helper element lazily as needed.\n   *\n   * @param {Node | undefined} node\n   * @protected\n   * @override\n   */\n  restoreDefaultNode() {\n    const { helperText } = this;\n\n    // No helper yet, create one.\n    if (helperText && helperText.trim() !== '') {\n      this.tagName = 'div';\n\n      const helperNode = this.attachDefaultNode();\n\n      // Observe the default node.\n      this.observeNode(helperNode);\n    }\n  }\n\n  /**\n   * Override method inherited from `SlotChildObserveController`\n   * to update the default helper element text content.\n   *\n   * @param {Node | undefined} node\n   * @protected\n   * @override\n   */\n  updateDefaultNode(node) {\n    if (node) {\n      node.textContent = this.helperText;\n    }\n\n    // Notify the host after update.\n    super.updateDefaultNode(node);\n  }\n\n  /**\n   * Override to observe the newly added custom node.\n   *\n   * @param {Node} node\n   * @protected\n   * @override\n   */\n  initCustomNode(node) {\n    // Notify the host about a custom slotted helper.\n    super.initCustomNode(node);\n\n    this.observeNode(node);\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { SlotChildObserveController } from '@vaadin/component-base/src/slot-child-observe-controller.js';\n\n/**\n * A controller to manage the label element.\n */\nexport class LabelController extends SlotChildObserveController {\n  constructor(host) {\n    super(host, 'label', 'label');\n  }\n\n  /**\n   * Set label based on corresponding host property.\n   *\n   * @param {string} label\n   */\n  setLabel(label) {\n    this.label = label;\n\n    // Restore the default label, if needed.\n    const labelNode = this.getSlotChild();\n    if (!labelNode) {\n      this.restoreDefaultNode();\n    }\n\n    // When default label is used, update it.\n    if (this.node === this.defaultNode) {\n      this.updateDefaultNode(this.node);\n    }\n  }\n\n  /**\n   * Override method inherited from `SlotChildObserveController`\n   * to restore and observe the default label element.\n   *\n   * @protected\n   * @override\n   */\n  restoreDefaultNode() {\n    const { label } = this;\n\n    // Restore the default label.\n    if (label && label.trim() !== '') {\n      const labelNode = this.attachDefaultNode();\n\n      // Observe the default label.\n      this.observeNode(labelNode);\n    }\n  }\n\n  /**\n   * Override method inherited from `SlotChildObserveController`\n   * to update the default label element text content.\n   *\n   * @param {Node | undefined} node\n   * @protected\n   * @override\n   */\n  updateDefaultNode(node) {\n    if (node) {\n      node.textContent = this.label;\n    }\n\n    // Notify the host after update.\n    super.updateDefaultNode(node);\n  }\n\n  /**\n   * Override to observe the newly added custom node.\n   *\n   * @param {Node} node\n   * @protected\n   * @override\n   */\n  initCustomNode(node) {\n    // Notify the host about adding a custom node.\n    super.initCustomNode(node);\n\n    this.observeNode(node);\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\nimport { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';\nimport { LabelController } from './label-controller.js';\n\n/**\n * A mixin to provide label via corresponding property or named slot.\n *\n * @polymerMixin\n * @mixes ControllerMixin\n */\nexport const LabelMixin = dedupingMixin(\n  (superclass) =>\n    class LabelMixinClass extends ControllerMixin(superclass) {\n      static get properties() {\n        return {\n          /**\n           * The label text for the input node.\n           * When no light dom defined via [slot=label], this value will be used.\n           */\n          label: {\n            type: String,\n            observer: '_labelChanged',\n          },\n        };\n      }\n\n      constructor() {\n        super();\n\n        this._labelController = new LabelController(this);\n\n        this._labelController.addEventListener('slot-content-changed', (event) => {\n          this.toggleAttribute('has-label', event.detail.hasContent);\n        });\n      }\n\n      /** @protected */\n      get _labelId() {\n        const node = this._labelNode;\n        return node && node.id;\n      }\n\n      /** @protected */\n      get _labelNode() {\n        return this._labelController.node;\n      }\n\n      /** @protected */\n      ready() {\n        super.ready();\n\n        this.addController(this._labelController);\n      }\n\n      /** @protected */\n      _labelChanged(label) {\n        this._labelController.setLabel(label);\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\n\n/**\n * A mixin to provide required state and validation logic.\n *\n * @polymerMixin\n */\nexport const ValidateMixin = dedupingMixin(\n  (superclass) =>\n    class ValidateMixinClass extends superclass {\n      static get properties() {\n        return {\n          /**\n           * Set to true when the field is invalid.\n           */\n          invalid: {\n            type: Boolean,\n            reflectToAttribute: true,\n            notify: true,\n            value: false,\n          },\n\n          /**\n           * Specifies that the user must fill in a value.\n           */\n          required: {\n            type: Boolean,\n            reflectToAttribute: true,\n          },\n        };\n      }\n\n      /**\n       * Validates the field and sets the `invalid` property based on the result.\n       *\n       * The method fires a `validated` event with the result of the validation.\n       *\n       * @return {boolean} True if the value is valid.\n       */\n      validate() {\n        const isValid = this.checkValidity();\n        this._setInvalid(!isValid);\n        this.dispatchEvent(new CustomEvent('validated', { detail: { valid: isValid } }));\n        return isValid;\n      }\n\n      /**\n       * Returns true if the field value satisfies all constraints (if any).\n       *\n       * @return {boolean}\n       */\n      checkValidity() {\n        return !this.required || !!this.value;\n      }\n\n      /**\n       * @param {boolean} invalid\n       * @protected\n       */\n      _setInvalid(invalid) {\n        if (this._shouldSetInvalid(invalid)) {\n          this.invalid = invalid;\n        }\n      }\n\n      /**\n       * Override this method to define whether the given `invalid` state should be set.\n       *\n       * @param {boolean} _invalid\n       * @return {boolean}\n       * @protected\n       */\n      _shouldSetInvalid(_invalid) {\n        return true;\n      }\n\n      /**\n       * Fired whenever the field is validated.\n       *\n       * @event validated\n       * @param {Object} detail\n       * @param {boolean} detail.valid the result of the validation.\n       */\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { FieldAriaController } from '@vaadin/a11y-base/src/field-aria-controller.js';\nimport { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';\nimport { ErrorController } from './error-controller.js';\nimport { HelperController } from './helper-controller.js';\nimport { LabelMixin } from './label-mixin.js';\nimport { ValidateMixin } from './validate-mixin.js';\n\n/**\n * A mixin to provide common field logic: label, error message and helper text.\n *\n * @polymerMixin\n * @mixes ControllerMixin\n * @mixes LabelMixin\n * @mixes ValidateMixin\n */\nexport const FieldMixin = (superclass) =>\n  class FieldMixinClass extends ValidateMixin(LabelMixin(ControllerMixin(superclass))) {\n    static get properties() {\n      return {\n        /**\n         * A target element to which ARIA attributes are set.\n         * @protected\n         */\n        ariaTarget: {\n          type: Object,\n          observer: '_ariaTargetChanged',\n        },\n\n        /**\n         * Error to show when the field is invalid.\n         *\n         * @attr {string} error-message\n         */\n        errorMessage: {\n          type: String,\n          observer: '_errorMessageChanged',\n        },\n\n        /**\n         * String used for the helper text.\n         * @attr {string} helper-text\n         */\n        helperText: {\n          type: String,\n          observer: '_helperTextChanged',\n        },\n\n        /**\n         * String used to label the component to screen reader users.\n         * @attr {string} accessible-name\n         */\n        accessibleName: {\n          type: String,\n          observer: '_accessibleNameChanged',\n        },\n\n        /**\n         * Id of the element used as label of the component to screen reader users.\n         * @attr {string} accessible-name-ref\n         */\n        accessibleNameRef: {\n          type: String,\n          observer: '_accessibleNameRefChanged',\n        },\n      };\n    }\n\n    static get observers() {\n      return ['_invalidChanged(invalid)', '_requiredChanged(required)'];\n    }\n\n    constructor() {\n      super();\n\n      this._fieldAriaController = new FieldAriaController(this);\n      this._helperController = new HelperController(this);\n      this._errorController = new ErrorController(this);\n\n      this._errorController.addEventListener('slot-content-changed', (event) => {\n        this.toggleAttribute('has-error-message', event.detail.hasContent);\n      });\n\n      this._labelController.addEventListener('slot-content-changed', (event) => {\n        const { hasContent, node } = event.detail;\n        this.__labelChanged(hasContent, node);\n      });\n\n      this._helperController.addEventListener('slot-content-changed', (event) => {\n        const { hasContent, node } = event.detail;\n        this.toggleAttribute('has-helper', hasContent);\n        this.__helperChanged(hasContent, node);\n      });\n    }\n\n    /**\n     * @protected\n     * @return {HTMLElement}\n     */\n    get _errorNode() {\n      return this._errorController.node;\n    }\n\n    /**\n     * @protected\n     * @return {HTMLElement}\n     */\n    get _helperNode() {\n      return this._helperController.node;\n    }\n\n    /** @protected */\n    ready() {\n      super.ready();\n\n      this.addController(this._fieldAriaController);\n      this.addController(this._helperController);\n      this.addController(this._errorController);\n    }\n\n    /** @private */\n    __helperChanged(hasHelper, helperNode) {\n      if (hasHelper) {\n        this._fieldAriaController.setHelperId(helperNode.id);\n      } else {\n        this._fieldAriaController.setHelperId(null);\n      }\n    }\n\n    /** @protected */\n    _accessibleNameChanged(accessibleName) {\n      this._fieldAriaController.setAriaLabel(accessibleName);\n    }\n\n    /** @protected */\n    _accessibleNameRefChanged(accessibleNameRef) {\n      this._fieldAriaController.setLabelId(accessibleNameRef, true);\n    }\n\n    /** @private */\n    __labelChanged(hasLabel, labelNode) {\n      // Label ID should be only added when the label content is present.\n      // Otherwise, it may conflict with an `aria-label` attribute possibly added by the user.\n      if (hasLabel) {\n        this._fieldAriaController.setLabelId(labelNode.id);\n      } else {\n        this._fieldAriaController.setLabelId(null);\n      }\n    }\n\n    /**\n     * @param {string | null | undefined} errorMessage\n     * @protected\n     */\n    _errorMessageChanged(errorMessage) {\n      this._errorController.setErrorMessage(errorMessage);\n    }\n\n    /**\n     * @param {string} helperText\n     * @protected\n     */\n    _helperTextChanged(helperText) {\n      this._helperController.setHelperText(helperText);\n    }\n\n    /**\n     * @param {HTMLElement | null | undefined} target\n     * @protected\n     */\n    _ariaTargetChanged(target) {\n      if (target) {\n        this._fieldAriaController.setTarget(target);\n      }\n    }\n\n    /**\n     * @param {boolean} required\n     * @protected\n     */\n    _requiredChanged(required) {\n      this._fieldAriaController.setRequired(required);\n    }\n\n    /**\n     * @param {boolean} invalid\n     * @protected\n     */\n    _invalidChanged(invalid) {\n      this._errorController.setInvalid(invalid);\n\n      // This timeout is needed to prevent NVDA from announcing the error message twice:\n      // 1. Once adding the `[role=alert]` attribute when updating `has-error-message` (OK).\n      // 2. Once linking the error ID with the ARIA target here (unwanted).\n      // Related issue: https://github.com/vaadin/web-components/issues/3061.\n      setTimeout(() => {\n        // Error message ID needs to be dynamically added / removed based on the validity\n        // Otherwise assistive technologies would announce the error, even if we hide it.\n        if (invalid) {\n          const node = this._errorNode;\n          this._fieldAriaController.setErrorId(node && node.id);\n        } else {\n          this._fieldAriaController.setErrorId(null);\n        }\n      });\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\n\n/**\n * A mixin to delegate properties and attributes to a target element.\n *\n * @polymerMixin\n */\nexport const DelegateStateMixin = dedupingMixin(\n  (superclass) =>\n    class DelegateStateMixinClass extends superclass {\n      static get properties() {\n        return {\n          /**\n           * A target element to which attributes and properties are delegated.\n           * @protected\n           */\n          stateTarget: {\n            type: Object,\n            observer: '_stateTargetChanged',\n          },\n        };\n      }\n\n      /**\n       * An array of the host attributes to delegate to the target element.\n       */\n      static get delegateAttrs() {\n        return [];\n      }\n\n      /**\n       * An array of the host properties to delegate to the target element.\n       */\n      static get delegateProps() {\n        return [];\n      }\n\n      /** @protected */\n      ready() {\n        super.ready();\n\n        this._createDelegateAttrsObserver();\n        this._createDelegatePropsObserver();\n      }\n\n      /** @protected */\n      _stateTargetChanged(target) {\n        if (target) {\n          this._ensureAttrsDelegated();\n          this._ensurePropsDelegated();\n        }\n      }\n\n      /** @protected */\n      _createDelegateAttrsObserver() {\n        this._createMethodObserver(`_delegateAttrsChanged(${this.constructor.delegateAttrs.join(', ')})`);\n      }\n\n      /** @protected */\n      _createDelegatePropsObserver() {\n        this._createMethodObserver(`_delegatePropsChanged(${this.constructor.delegateProps.join(', ')})`);\n      }\n\n      /** @protected */\n      _ensureAttrsDelegated() {\n        this.constructor.delegateAttrs.forEach((name) => {\n          this._delegateAttribute(name, this[name]);\n        });\n      }\n\n      /** @protected */\n      _ensurePropsDelegated() {\n        this.constructor.delegateProps.forEach((name) => {\n          this._delegateProperty(name, this[name]);\n        });\n      }\n\n      /** @protected */\n      _delegateAttrsChanged(...values) {\n        this.constructor.delegateAttrs.forEach((name, index) => {\n          this._delegateAttribute(name, values[index]);\n        });\n      }\n\n      /** @protected */\n      _delegatePropsChanged(...values) {\n        this.constructor.delegateProps.forEach((name, index) => {\n          this._delegateProperty(name, values[index]);\n        });\n      }\n\n      /** @protected */\n      _delegateAttribute(name, value) {\n        if (!this.stateTarget) {\n          return;\n        }\n\n        if (name === 'invalid') {\n          this._delegateAttribute('aria-invalid', value ? 'true' : false);\n        }\n\n        if (typeof value === 'boolean') {\n          this.stateTarget.toggleAttribute(name, value);\n        } else if (value) {\n          this.stateTarget.setAttribute(name, value);\n        } else {\n          this.stateTarget.removeAttribute(name);\n        }\n      }\n\n      /** @protected */\n      _delegateProperty(name, value) {\n        if (!this.stateTarget) {\n          return;\n        }\n\n        this.stateTarget[name] = value;\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\nimport { DelegateStateMixin } from '@vaadin/component-base/src/delegate-state-mixin.js';\nimport { InputMixin } from './input-mixin.js';\nimport { ValidateMixin } from './validate-mixin.js';\n\n/**\n * A mixin to combine multiple input validation constraints.\n *\n * @polymerMixin\n * @mixes DelegateStateMixin\n * @mixes InputMixin\n * @mixes ValidateMixin\n */\nexport const InputConstraintsMixin = dedupingMixin(\n  (superclass) =>\n    class InputConstraintsMixinClass extends DelegateStateMixin(ValidateMixin(InputMixin(superclass))) {\n      /**\n       * An array of attributes which participate in the input validation.\n       * Changing these attributes will cause the input to re-validate.\n       *\n       * IMPORTANT: The attributes should be properly delegated to the input element\n       * from the host using `delegateAttrs` getter (see `DelegateStateMixin`).\n       * The `required` attribute is already delegated.\n       */\n      static get constraints() {\n        return ['required'];\n      }\n\n      static get delegateAttrs() {\n        return [...super.delegateAttrs, 'required'];\n      }\n\n      /** @protected */\n      ready() {\n        super.ready();\n\n        this._createConstraintsObserver();\n      }\n\n      /**\n       * Returns true if the current input value satisfies all constraints (if any).\n       * @return {boolean}\n       */\n      checkValidity() {\n        if (this.inputElement && this._hasValidConstraints(this.constructor.constraints.map((c) => this[c]))) {\n          return this.inputElement.checkValidity();\n        }\n        return !this.invalid;\n      }\n\n      /**\n       * Returns true if some of the provided set of constraints are valid.\n       * @param {Array} constraints\n       * @return {boolean}\n       * @protected\n       */\n      _hasValidConstraints(constraints) {\n        return constraints.some((c) => this.__isValidConstraint(c));\n      }\n\n      /**\n       * Override this method to customize setting up constraints observer.\n       * @protected\n       */\n      _createConstraintsObserver() {\n        // This complex observer needs to be added dynamically instead of using `static get observers()`\n        // to make it possible to tweak this behavior in classes that apply this mixin.\n        this._createMethodObserver(`_constraintsChanged(stateTarget, ${this.constructor.constraints.join(', ')})`);\n      }\n\n      /**\n       * Override this method to implement custom validation constraints.\n       * @param {HTMLElement | undefined} stateTarget\n       * @param {unknown[]} constraints\n       * @protected\n       */\n      _constraintsChanged(stateTarget, ...constraints) {\n        // The input element's validity cannot be determined until\n        // all the necessary constraint attributes aren't set on it.\n        if (!stateTarget) {\n          return;\n        }\n\n        const hasConstraints = this._hasValidConstraints(constraints);\n        const isLastConstraintRemoved = this.__previousHasConstraints && !hasConstraints;\n\n        if ((this._hasValue || this.invalid) && hasConstraints) {\n          this.validate();\n        } else if (isLastConstraintRemoved) {\n          this._setInvalid(false);\n        }\n\n        this.__previousHasConstraints = hasConstraints;\n      }\n\n      /**\n       * Override an event listener inherited from `InputMixin`\n       * to capture native `change` event and make sure that\n       * a new one is dispatched after validation runs.\n       * @param {Event} event\n       * @protected\n       * @override\n       */\n      _onChange(event) {\n        event.stopPropagation();\n\n        this.validate();\n\n        this.dispatchEvent(\n          new CustomEvent('change', {\n            detail: {\n              sourceEvent: event,\n            },\n            bubbles: event.bubbles,\n            cancelable: event.cancelable,\n          }),\n        );\n      }\n\n      /** @private */\n      __isValidConstraint(constraint) {\n        // 0 is valid for `minlength` and `maxlength`\n        return Boolean(constraint) || constraint === 0;\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';\n\nconst stylesMap = new WeakMap();\n\n/**\n * Get all the styles inserted into root.\n * @param {DocumentOrShadowRoot} root\n * @return {Set<string>}\n */\nfunction getRootStyles(root) {\n  if (!stylesMap.has(root)) {\n    stylesMap.set(root, new Set());\n  }\n\n  return stylesMap.get(root);\n}\n\n/**\n * Insert styles into the root.\n * @param {string} styles\n * @param {DocumentOrShadowRoot} root\n */\nfunction insertStyles(styles, root) {\n  const style = document.createElement('style');\n  style.textContent = styles;\n\n  if (root === document) {\n    document.head.appendChild(style);\n  } else {\n    root.insertBefore(style, root.firstChild);\n  }\n}\n\n/**\n * Mixin to insert styles into the outer scope to handle slotted components.\n * This is useful e.g. to hide native `<input type=\"number\">` controls.\n *\n * @polymerMixin\n */\nexport const SlotStylesMixin = dedupingMixin(\n  (superclass) =>\n    class SlotStylesMixinClass extends superclass {\n      /**\n       * List of styles to insert into root.\n       * @protected\n       */\n      get slotStyles() {\n        return {};\n      }\n\n      /** @protected */\n      connectedCallback() {\n        super.connectedCallback();\n\n        this.__applySlotStyles();\n      }\n\n      /** @private */\n      __applySlotStyles() {\n        const root = this.getRootNode();\n        const rootStyles = getRootStyles(root);\n\n        this.slotStyles.forEach((styles) => {\n          if (!rootStyles.has(styles)) {\n            insertStyles(styles, root);\n            rootStyles.add(styles);\n          }\n        });\n      }\n    },\n);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { DelegateFocusMixin } from '@vaadin/a11y-base/src/delegate-focus-mixin.js';\nimport { KeyboardMixin } from '@vaadin/a11y-base/src/keyboard-mixin.js';\nimport { timeOut } from '@vaadin/component-base/src/async.js';\nimport { Debouncer } from '@vaadin/component-base/src/debounce.js';\nimport { ClearButtonMixin } from './clear-button-mixin.js';\nimport { FieldMixin } from './field-mixin.js';\nimport { InputConstraintsMixin } from './input-constraints-mixin.js';\nimport { SlotStylesMixin } from './slot-styles-mixin.js';\n\n/**\n * A mixin to provide shared logic for the editable form input controls.\n *\n * @polymerMixin\n * @mixes DelegateFocusMixin\n * @mixes FieldMixin\n * @mixes InputConstraintsMixin\n * @mixes KeyboardMixin\n * @mixes ClearButtonMixin\n * @mixes SlotStylesMixin\n */\nexport const InputControlMixin = (superclass) =>\n  class InputControlMixinClass extends SlotStylesMixin(\n    DelegateFocusMixin(InputConstraintsMixin(FieldMixin(ClearButtonMixin(KeyboardMixin(superclass))))),\n  ) {\n    static get properties() {\n      return {\n        /**\n         * A pattern matched against individual characters the user inputs.\n         *\n         * When set, the field will prevent:\n         * - `keydown` events if the entered key doesn't match `/^allowedCharPattern$/`\n         * - `paste` events if the pasted text doesn't match `/^allowedCharPattern*$/`\n         * - `drop` events if the dropped text doesn't match `/^allowedCharPattern*$/`\n         *\n         * For example, to allow entering only numbers and minus signs, use:\n         * `allowedCharPattern = \"[\\\\d-]\"`\n         * @attr {string} allowed-char-pattern\n         */\n        allowedCharPattern: {\n          type: String,\n          observer: '_allowedCharPatternChanged',\n        },\n\n        /**\n         * If true, the input text gets fully selected when the field is focused using click or touch / tap.\n         */\n        autoselect: {\n          type: Boolean,\n          value: false,\n        },\n\n        /**\n         * The name of this field.\n         */\n        name: {\n          type: String,\n          reflectToAttribute: true,\n        },\n\n        /**\n         * A hint to the user of what can be entered in the field.\n         */\n        placeholder: {\n          type: String,\n          reflectToAttribute: true,\n        },\n\n        /**\n         * When present, it specifies that the field is read-only.\n         */\n        readonly: {\n          type: Boolean,\n          value: false,\n          reflectToAttribute: true,\n        },\n\n        /**\n         * The text usually displayed in a tooltip popup when the mouse is over the field.\n         */\n        title: {\n          type: String,\n          reflectToAttribute: true,\n        },\n      };\n    }\n\n    static get delegateAttrs() {\n      return [...super.delegateAttrs, 'name', 'type', 'placeholder', 'readonly', 'invalid', 'title'];\n    }\n\n    constructor() {\n      super();\n\n      this._boundOnPaste = this._onPaste.bind(this);\n      this._boundOnDrop = this._onDrop.bind(this);\n      this._boundOnBeforeInput = this._onBeforeInput.bind(this);\n    }\n\n    /** @protected */\n    get slotStyles() {\n      // Needed for Safari, where ::slotted(...)::placeholder does not work\n      return [\n        `\n          :is(input[slot='input'], textarea[slot='textarea'])::placeholder {\n            font: inherit;\n            color: inherit;\n          }\n        `,\n      ];\n    }\n\n    /**\n     * Override an event listener from `DelegateFocusMixin`.\n     * @param {FocusEvent} event\n     * @protected\n     * @override\n     */\n    _onFocus(event) {\n      super._onFocus(event);\n\n      if (this.autoselect && this.inputElement) {\n        this.inputElement.select();\n      }\n    }\n\n    /**\n     * Override an event listener inherited from `InputMixin`\n     * to capture native `change` event and make sure that\n     * a new one is dispatched after validation runs.\n     * @param {Event} event\n     * @protected\n     * @override\n     */\n    _onChange(event) {\n      event.stopPropagation();\n\n      this.validate();\n\n      this.dispatchEvent(\n        new CustomEvent('change', {\n          detail: {\n            sourceEvent: event,\n          },\n          bubbles: event.bubbles,\n          cancelable: event.cancelable,\n        }),\n      );\n    }\n\n    /**\n     * Override a method from `InputMixin`.\n     * @param {!HTMLElement} input\n     * @protected\n     * @override\n     */\n    _addInputListeners(input) {\n      super._addInputListeners(input);\n\n      input.addEventListener('paste', this._boundOnPaste);\n      input.addEventListener('drop', this._boundOnDrop);\n      input.addEventListener('beforeinput', this._boundOnBeforeInput);\n    }\n\n    /**\n     * Override a method from `InputMixin`.\n     * @param {!HTMLElement} input\n     * @protected\n     * @override\n     */\n    _removeInputListeners(input) {\n      super._removeInputListeners(input);\n\n      input.removeEventListener('paste', this._boundOnPaste);\n      input.removeEventListener('drop', this._boundOnDrop);\n      input.removeEventListener('beforeinput', this._boundOnBeforeInput);\n    }\n\n    /**\n     * Override an event listener from `KeyboardMixin`.\n     * @param {!KeyboardEvent} event\n     * @protected\n     * @override\n     */\n    _onKeyDown(event) {\n      super._onKeyDown(event);\n\n      if (this.allowedCharPattern && !this.__shouldAcceptKey(event)) {\n        event.preventDefault();\n        this._markInputPrevented();\n      }\n    }\n\n    /** @protected */\n    _markInputPrevented() {\n      // Add input-prevented attribute for 200ms\n      this.setAttribute('input-prevented', '');\n      this._preventInputDebouncer = Debouncer.debounce(this._preventInputDebouncer, timeOut.after(200), () => {\n        this.removeAttribute('input-prevented');\n      });\n    }\n\n    /** @private */\n    __shouldAcceptKey(event) {\n      return (\n        event.metaKey ||\n        event.ctrlKey ||\n        !event.key || // Allow typing anything if event.key is not supported\n        event.key.length !== 1 || // Allow \"Backspace\", \"ArrowLeft\" etc.\n        this.__allowedCharRegExp.test(event.key)\n      );\n    }\n\n    /** @private */\n    _onPaste(e) {\n      if (this.allowedCharPattern) {\n        const pastedText = e.clipboardData.getData('text');\n        if (!this.__allowedTextRegExp.test(pastedText)) {\n          e.preventDefault();\n          this._markInputPrevented();\n        }\n      }\n    }\n\n    /** @private */\n    _onDrop(e) {\n      if (this.allowedCharPattern) {\n        const draggedText = e.dataTransfer.getData('text');\n        if (!this.__allowedTextRegExp.test(draggedText)) {\n          e.preventDefault();\n          this._markInputPrevented();\n        }\n      }\n    }\n\n    /** @private */\n    _onBeforeInput(e) {\n      // The `beforeinput` event covers all the cases for `allowedCharPattern`: keyboard, pasting and dropping,\n      // but it is still experimental technology so we can't rely on it. It's used here just as an additional check,\n      // because it seems to be the only way to detect and prevent specific keys on mobile devices.\n      // See https://github.com/vaadin/vaadin-text-field/issues/429\n      if (this.allowedCharPattern && e.data && !this.__allowedTextRegExp.test(e.data)) {\n        e.preventDefault();\n        this._markInputPrevented();\n      }\n    }\n\n    /** @private */\n    _allowedCharPatternChanged(charPattern) {\n      if (charPattern) {\n        try {\n          this.__allowedCharRegExp = new RegExp(`^${charPattern}$`, 'u');\n          this.__allowedTextRegExp = new RegExp(`^${charPattern}*$`, 'u');\n        } catch (e) {\n          console.error(e);\n        }\n      }\n    }\n\n    /**\n     * Fired when the user commits a value change.\n     *\n     * @event change\n     */\n\n    /**\n     * Fired when the value is changed by the user: on every typing keystroke,\n     * and the value is cleared using the clear button.\n     *\n     * @event input\n     */\n  };\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { SlotController } from '@vaadin/component-base/src/slot-controller.js';\n\n/**\n * A controller to create and initialize slotted `<input>` element.\n */\nexport class InputController extends SlotController {\n  constructor(host, callback) {\n    super(host, 'input', 'input', {\n      initializer: (node, host) => {\n        if (host.value) {\n          node.setAttribute('value', host.value);\n        }\n        if (host.type) {\n          node.setAttribute('type', host.type);\n        }\n\n        // Ensure every instance has unique ID\n        node.id = this.defaultId;\n\n        if (typeof callback === 'function') {\n          callback(node);\n        }\n      },\n      useUniqueId: true,\n    });\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * A controller for linking a `<label>` element with an `<input>` element.\n */\nexport class LabelledInputController {\n  constructor(input, labelController) {\n    this.input = input;\n    this.__preventDuplicateLabelClick = this.__preventDuplicateLabelClick.bind(this);\n\n    labelController.addEventListener('slot-content-changed', (event) => {\n      this.__initLabel(event.detail.node);\n    });\n\n    // Initialize the default label element\n    this.__initLabel(labelController.node);\n  }\n\n  /**\n   * @param {HTMLElement} label\n   * @private\n   */\n  __initLabel(label) {\n    if (label) {\n      label.addEventListener('click', this.__preventDuplicateLabelClick);\n\n      if (this.input) {\n        label.setAttribute('for', this.input.id);\n      }\n    }\n  }\n\n  /**\n   * The native platform fires an event for both the click on the label, and also\n   * the subsequent click on the native input element caused by label click.\n   * This results in two click events arriving at the host, but we only want one.\n   * This method prevents the duplicate click and ensures the correct isTrusted event\n   * with the correct event.target arrives at the host.\n   * @private\n   */\n  __preventDuplicateLabelClick() {\n    const inputClickHandler = (e) => {\n      e.stopImmediatePropagation();\n      this.input.removeEventListener('click', inputClickHandler);\n    };\n    this.input.addEventListener('click', inputClickHandler);\n  }\n}\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd..\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { css } from 'lit';\n\nexport const clearButton = css`\n  [part='clear-button'] {\n    display: none;\n    cursor: default;\n  }\n\n  [part='clear-button']::before {\n    content: '\\\\2715';\n  }\n\n  :host([clear-button-visible][has-value]:not([disabled]):not([readonly])) [part='clear-button'] {\n    display: block;\n  }\n`;\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd..\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { clearButton } from './clear-button-styles.js';\nimport { fieldShared } from './field-shared-styles.js';\nimport { inputFieldContainer } from './input-field-container-styles.js';\n\nexport const inputFieldShared = [fieldShared, inputFieldContainer, clearButton];\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd..\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { css } from 'lit';\n\nexport const fieldShared = css`\n  :host {\n    display: inline-flex;\n    outline: none;\n  }\n\n  :host::before {\n    content: '\\\\2003';\n    width: 0;\n    display: inline-block;\n    /* Size and position this element on the same vertical position as the input-field element\n          to make vertical align for the host element work as expected */\n  }\n\n  :host([hidden]) {\n    display: none !important;\n  }\n\n  :host(:not([has-label])) [part='label'] {\n    display: none;\n  }\n\n  @media (forced-colors: active) {\n    :host(:not([readonly])) [part='input-field'] {\n      outline: 1px solid;\n      outline-offset: -1px;\n    }\n    :host([focused]) [part='input-field'] {\n      outline-width: 2px;\n    }\n    :host([disabled]) [part='input-field'] {\n      outline-color: GrayText;\n    }\n  }\n`;\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd..\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { css } from 'lit';\n\nexport const inputFieldContainer = css`\n  [class$='container'] {\n    display: flex;\n    flex-direction: column;\n    min-width: 100%;\n    max-width: 100%;\n    width: var(--vaadin-field-default-width, 12em);\n  }\n`;\n","/**\n * @license\n * Copyright (c) 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * A mixin that forwards CSS class names to the internal overlay element\n * by setting the `overlayClass` property or `overlay-class` attribute.\n *\n * @polymerMixin\n */\nexport const OverlayClassMixin = (superclass) =>\n  class OverlayClassMixinClass extends superclass {\n    static get properties() {\n      return {\n        /**\n         * A space-delimited list of CSS class names to set on the overlay element.\n         * This property does not affect other CSS class names set manually via JS.\n         *\n         * Note, if the CSS class name was set with this property, clearing it will\n         * remove it from the overlay, even if the same class name was also added\n         * manually, e.g. by using `classList.add()` in the `renderer` function.\n         *\n         * @attr {string} overlay-class\n         */\n        overlayClass: {\n          type: String,\n        },\n\n        /**\n         * An overlay element on which CSS class names are set.\n         *\n         * @protected\n         */\n        _overlayElement: {\n          type: Object,\n        },\n      };\n    }\n\n    static get observers() {\n      return ['__updateOverlayClassNames(overlayClass, _overlayElement)'];\n    }\n\n    /** @private */\n    __updateOverlayClassNames(overlayClass, overlayElement) {\n      if (!overlayElement) {\n        return;\n      }\n\n      // Overlay is set but overlayClass is not set\n      if (overlayClass === undefined) {\n        return;\n      }\n\n      const { classList } = overlayElement;\n\n      if (!this.__initialClasses) {\n        this.__initialClasses = new Set(classList);\n      }\n\n      if (Array.isArray(this.__previousClasses)) {\n        // Remove old classes that no longer apply\n        const classesToRemove = this.__previousClasses.filter((name) => !this.__initialClasses.has(name));\n        if (classesToRemove.length > 0) {\n          classList.remove(...classesToRemove);\n        }\n      }\n\n      // Add new classes based on the overlayClass\n      const classesToAdd = typeof overlayClass === 'string' ? overlayClass.split(' ') : [];\n      if (classesToAdd.length > 0) {\n        classList.add(...classesToAdd);\n      }\n\n      this.__previousClasses = classesToAdd;\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * A controller which prevents the virtual keyboard from showing up on mobile devices\n * when the field's overlay is closed.\n */\nexport class VirtualKeyboardController {\n  /**\n   * @param {{ inputElement?: HTMLElement; opened: boolean } & HTMLElement} host\n   */\n  constructor(host) {\n    this.host = host;\n\n    host.addEventListener('opened-changed', () => {\n      if (!host.opened) {\n        // Prevent opening the virtual keyboard when the input gets re-focused on dropdown close\n        this.__setVirtualKeyboardEnabled(false);\n      }\n    });\n\n    // Re-enable virtual keyboard on blur, so it gets opened when the field is focused again\n    host.addEventListener('blur', () => this.__setVirtualKeyboardEnabled(true));\n\n    // Re-enable the virtual keyboard whenever the field is touched\n    host.addEventListener('touchstart', () => this.__setVirtualKeyboardEnabled(true));\n  }\n\n  /** @private */\n  __setVirtualKeyboardEnabled(value) {\n    if (this.host.inputElement) {\n      this.host.inputElement.inputMode = value ? '' : 'none';\n    }\n  }\n}\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { hideOthers } from '@vaadin/a11y-base/src/aria-hidden.js';\nimport { DelegateFocusMixin } from '@vaadin/a11y-base/src/delegate-focus-mixin.js';\nimport { KeyboardMixin } from '@vaadin/a11y-base/src/keyboard-mixin.js';\nimport { isIOS } from '@vaadin/component-base/src/browser-utils.js';\nimport { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';\nimport { MediaQueryController } from '@vaadin/component-base/src/media-query-controller.js';\nimport { OverlayClassMixin } from '@vaadin/component-base/src/overlay-class-mixin.js';\nimport { InputConstraintsMixin } from '@vaadin/field-base/src/input-constraints-mixin.js';\nimport { VirtualKeyboardController } from '@vaadin/field-base/src/virtual-keyboard-controller.js';\nimport {\n  dateAllowed,\n  dateEquals,\n  extractDateParts,\n  getAdjustedYear,\n  getClosestDate,\n  parseDate,\n} from './vaadin-date-picker-helper.js';\n\n/**\n * @polymerMixin\n * @mixes ControllerMixin\n * @mixes DelegateFocusMixin\n * @mixes InputConstraintsMixin\n * @mixes KeyboardMixin\n * @mixes OverlayClassMixin\n * @param {function(new:HTMLElement)} subclass\n */\nexport const DatePickerMixin = (subclass) =>\n  class DatePickerMixinClass extends OverlayClassMixin(\n    ControllerMixin(DelegateFocusMixin(InputConstraintsMixin(KeyboardMixin(subclass)))),\n  ) {\n    static get properties() {\n      return {\n        /**\n         * The current selected date.\n         * @type {Date | undefined}\n         * @protected\n         */\n        _selectedDate: {\n          type: Date,\n        },\n\n        /**\n         * @type {Date | undefined}\n         * @protected\n         */\n        _focusedDate: Date,\n\n        /**\n         * Selected date.\n         *\n         * Supported date formats:\n         * - ISO 8601 `\"YYYY-MM-DD\"` (default)\n         * - 6-digit extended ISO 8601 `\"+YYYYYY-MM-DD\"`, `\"-YYYYYY-MM-DD\"`\n         *\n         * @type {string}\n         */\n        value: {\n          type: String,\n          notify: true,\n          value: '',\n        },\n\n        /**\n         * Date which should be visible when there is no value selected.\n         *\n         * The same date formats as for the `value` property are supported.\n         * @attr {string} initial-position\n         */\n        initialPosition: String,\n\n        /**\n         * Set true to open the date selector overlay.\n         */\n        opened: {\n          type: Boolean,\n          reflectToAttribute: true,\n          notify: true,\n          observer: '_openedChanged',\n        },\n\n        /**\n         * Set true to prevent the overlay from opening automatically.\n         * @attr {boolean} auto-open-disabled\n         */\n        autoOpenDisabled: Boolean,\n\n        /**\n         * Set true to display ISO-8601 week numbers in the calendar. Notice that\n         * displaying week numbers is only supported when `i18n.firstDayOfWeek`\n         * is 1 (Monday).\n         * @attr {boolean} show-week-numbers\n         */\n        showWeekNumbers: {\n          type: Boolean,\n          value: false,\n        },\n\n        /**\n         * @type {boolean}\n         * @protected\n         */\n        _fullscreen: {\n          type: Boolean,\n          value: false,\n        },\n\n        /**\n         * @type {string}\n         * @protected\n         */\n        _fullscreenMediaQuery: {\n          value: '(max-width: 420px), (max-height: 420px)',\n        },\n\n        /**\n         * The object used to localize this component.\n         * To change the default localization, replace the entire\n         * `i18n` object with a custom one.\n         *\n         * To update individual properties, extend the existing i18n object like so:\n         * ```\n         * datePicker.i18n = { ...datePicker.i18n, {\n         *   formatDate: date => { ... },\n         *   parseDate: value => { ... },\n         * }};\n         * ```\n         *\n         * The object has the following JSON structure and default values:\n         *\n         * ```\n         * {\n         *   // An array with the full names of months starting\n         *   // with January.\n         *   monthNames: [\n         *     'January', 'February', 'March', 'April', 'May',\n         *     'June', 'July', 'August', 'September',\n         *     'October', 'November', 'December'\n         *   ],\n         *\n         *   // An array of weekday names starting with Sunday. Used\n         *   // in screen reader announcements.\n         *   weekdays: [\n         *     'Sunday', 'Monday', 'Tuesday', 'Wednesday',\n         *     'Thursday', 'Friday', 'Saturday'\n         *   ],\n         *\n         *   // An array of short weekday names starting with Sunday.\n         *   // Displayed in the calendar.\n         *   weekdaysShort: [\n         *     'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'\n         *   ],\n         *\n         *   // An integer indicating the first day of the week\n         *   // (0 = Sunday, 1 = Monday, etc.).\n         *   firstDayOfWeek: 0,\n         *\n         *   // Translation of the Today shortcut button text.\n         *   today: 'Today',\n         *\n         *   // Translation of the Cancel button text.\n         *   cancel: 'Cancel',\n         *\n         *   // Used for adjusting the year value when parsing dates with short years.\n         *   // The year values between 0 and 99 are evaluated and adjusted.\n         *   // Example: for a referenceDate of 1970-10-30;\n         *   //   dateToBeParsed: 40-10-30, result: 1940-10-30\n         *   //   dateToBeParsed: 80-10-30, result: 1980-10-30\n         *   //   dateToBeParsed: 10-10-30, result: 2010-10-30\n         *   // Supported date format: ISO 8601 `\"YYYY-MM-DD\"` (default)\n         *   // The default value is the current date.\n         *   referenceDate: '',\n         *\n         *   // A function to format given `Object` as\n         *   // date string. Object is in the format `{ day: ..., month: ..., year: ... }`\n         *   // Note: The argument month is 0-based. This means that January = 0 and December = 11.\n         *   formatDate: d => {\n         *     // returns a string representation of the given\n         *     // object in 'MM/DD/YYYY' -format\n         *   },\n         *\n         *   // A function to parse the given text to an `Object` in the format `{ day: ..., month: ..., year: ... }`.\n         *   // Must properly parse (at least) text formatted by `formatDate`.\n         *   // Setting the property to null will disable keyboard input feature.\n         *   // Note: The argument month is 0-based. This means that January = 0 and December = 11.\n         *   parseDate: text => {\n         *     // Parses a string in 'MM/DD/YY', 'MM/DD' or 'DD' -format to\n         *     // an `Object` in the format `{ day: ..., month: ..., year: ... }`.\n         *   }\n         *\n         *   // A function to format given `monthName` and\n         *   // `fullYear` integer as calendar title string.\n         *   formatTitle: (monthName, fullYear) => {\n         *     return monthName + ' ' + fullYear;\n         *   }\n         * }\n         * ```\n         *\n         * @type {!DatePickerI18n}\n         * @default {English/US}\n         */\n        i18n: {\n          type: Object,\n          value: () => {\n            return {\n              monthNames: [\n                'January',\n                'February',\n                'March',\n                'April',\n                'May',\n                'June',\n                'July',\n                'August',\n                'September',\n                'October',\n                'November',\n                'December',\n              ],\n              weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],\n              weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],\n              firstDayOfWeek: 0,\n              today: 'Today',\n              cancel: 'Cancel',\n              referenceDate: '',\n              formatDate(d) {\n                const yearStr = String(d.year).replace(/\\d+/u, (y) => '0000'.substr(y.length) + y);\n                return [d.month + 1, d.day, yearStr].join('/');\n              },\n              parseDate(text) {\n                const parts = text.split('/');\n                const today = new Date();\n                let date,\n                  month = today.getMonth(),\n                  year = today.getFullYear();\n\n                if (parts.length === 3) {\n                  month = parseInt(parts[0]) - 1;\n                  date = parseInt(parts[1]);\n                  year = parseInt(parts[2]);\n                  if (parts[2].length < 3 && year >= 0) {\n                    const usedReferenceDate = this.referenceDate ? parseDate(this.referenceDate) : new Date();\n                    year = getAdjustedYear(usedReferenceDate, year, month, date);\n                  }\n                } else if (parts.length === 2) {\n                  month = parseInt(parts[0]) - 1;\n                  date = parseInt(parts[1]);\n                } else if (parts.length === 1) {\n                  date = parseInt(parts[0]);\n                }\n\n                if (date !== undefined) {\n                  return { day: date, month, year };\n                }\n              },\n              formatTitle: (monthName, fullYear) => {\n                return `${monthName} ${fullYear}`;\n              },\n            };\n          },\n        },\n\n        /**\n         * The earliest date that can be selected. All earlier dates will be disabled.\n         *\n         * Supported date formats:\n         * - ISO 8601 `\"YYYY-MM-DD\"` (default)\n         * - 6-digit extended ISO 8601 `\"+YYYYYY-MM-DD\"`, `\"-YYYYYY-MM-DD\"`\n         *\n         * @type {string | undefined}\n         */\n        min: {\n          type: String,\n        },\n\n        /**\n         * The latest date that can be selected. All later dates will be disabled.\n         *\n         * Supported date formats:\n         * - ISO 8601 `\"YYYY-MM-DD\"` (default)\n         * - 6-digit extended ISO 8601 `\"+YYYYYY-MM-DD\"`, `\"-YYYYYY-MM-DD\"`\n         *\n         * @type {string | undefined}\n         */\n        max: {\n          type: String,\n        },\n\n        /**\n         * The earliest date that can be selected. All earlier dates will be disabled.\n         * @type {Date | undefined}\n         * @protected\n         */\n        _minDate: {\n          type: Date,\n          computed: '__computeMinOrMaxDate(min)',\n        },\n\n        /**\n         * The latest date that can be selected. All later dates will be disabled.\n         * @type {Date | undefined}\n         * @protected\n         */\n        _maxDate: {\n          type: Date,\n          computed: '__computeMinOrMaxDate(max)',\n        },\n\n        /** @private */\n        _noInput: {\n          type: Boolean,\n          computed: '_isNoInput(inputElement, _fullscreen, _ios, i18n, opened, autoOpenDisabled)',\n        },\n\n        /** @private */\n        _ios: {\n          type: Boolean,\n          value: isIOS,\n        },\n\n        /** @private */\n        _focusOverlayOnOpen: Boolean,\n\n        /** @private */\n        _overlayContent: Object,\n\n        /**\n         * In date-picker, unlike other components extending `InputMixin`,\n         * the property indicates true only if the input has been entered by the user.\n         * In the case of programmatic changes, the property is reset to false.\n         * Read more about why this workaround is needed:\n         * https://github.com/vaadin/web-components/issues/5639\n         *\n         * @protected\n         * @override\n         */\n        _hasInputValue: {\n          type: Boolean,\n        },\n      };\n    }\n\n    static get observers() {\n      return [\n        '_selectedDateChanged(_selectedDate, i18n.formatDate)',\n        '_focusedDateChanged(_focusedDate, i18n.formatDate)',\n        '__updateOverlayContent(_overlayContent, i18n, label, _minDate, _maxDate, _focusedDate, _selectedDate, showWeekNumbers)',\n        '__updateOverlayContentTheme(_overlayContent, _theme)',\n        '__updateOverlayContentFullScreen(_overlayContent, _fullscreen)',\n      ];\n    }\n\n    static get constraints() {\n      return [...super.constraints, 'min', 'max'];\n    }\n\n    constructor() {\n      super();\n\n      this._boundOnClick = this._onClick.bind(this);\n      this._boundOnScroll = this._onScroll.bind(this);\n      this._boundOverlayRenderer = this._overlayRenderer.bind(this);\n    }\n\n    /**\n     * @override\n     * @protected\n     */\n    get _inputElementValue() {\n      return super._inputElementValue;\n    }\n\n    /**\n     * The setter is overridden to reset the `_hasInputValue` property\n     * to false when the input element's value is updated programmatically.\n     * In date-picker, `_hasInputValue` is supposed to indicate true only\n     * if the input has been entered by the user.\n     * Read more about why this workaround is needed:\n     * https://github.com/vaadin/web-components/issues/5639\n     *\n     * @override\n     * @protected\n     */\n    set _inputElementValue(value) {\n      super._inputElementValue = value;\n      this._hasInputValue = false;\n    }\n\n    /**\n     * Override a getter from `InputControlMixin` to make it optional\n     * and to prevent warning when a clear button is missing,\n     * for example when using <vaadin-date-picker-light>.\n     * @protected\n     * @return {Element | null | undefined}\n     */\n    get clearElement() {\n      return null;\n    }\n\n    /** @private */\n    get _nativeInput() {\n      if (this.inputElement) {\n        // TODO: support focusElement for backwards compatibility\n        return this.inputElement.focusElement || this.inputElement;\n      }\n      return null;\n    }\n\n    /**\n     * Override an event listener from `DelegateFocusMixin`\n     * @protected\n     */\n    _onFocus(event) {\n      super._onFocus(event);\n\n      if (this._noInput) {\n        event.target.blur();\n      }\n    }\n\n    /**\n     * Override an event listener from `DelegateFocusMixin`\n     * @protected\n     */\n    _onBlur(event) {\n      super._onBlur(event);\n\n      if (!this.opened) {\n        if (this.autoOpenDisabled) {\n          this._selectParsedOrFocusedDate();\n        }\n\n        // Do not validate when focusout is caused by document\n        // losing focus, which happens on browser tab switch.\n        if (document.hasFocus()) {\n          this.validate();\n        }\n\n        if (this._inputElementValue === '' && this.value !== '') {\n          this.value = '';\n        }\n      }\n    }\n\n    /** @protected */\n    ready() {\n      super.ready();\n\n      this.addEventListener('click', this._boundOnClick);\n\n      this.addController(\n        new MediaQueryController(this._fullscreenMediaQuery, (matches) => {\n          this._fullscreen = matches;\n        }),\n      );\n\n      this.addController(new VirtualKeyboardController(this));\n\n      const overlay = this.$.overlay;\n      this._overlayElement = overlay;\n\n      overlay.renderer = this._boundOverlayRenderer;\n\n      this.addEventListener('mousedown', () => this.__bringToFront());\n      this.addEventListener('touchstart', () => this.__bringToFront());\n    }\n\n    /** @protected */\n    disconnectedCallback() {\n      super.disconnectedCallback();\n\n      this.opened = false;\n    }\n\n    /**\n     * Override Polymer lifecycle callback to dispatch `change` event if needed.\n     * This is necessary to ensure `change` is fired after `value-changed`.\n     *\n     * @param {!Object} currentProps Current accessor values\n     * @param {?Object} changedProps Properties changed since the last call\n     * @param {?Object} oldProps Previous values for each changed property\n     * @protected\n     * @override\n     */\n    _propertiesChanged(currentProps, changedProps, oldProps) {\n      super._propertiesChanged(currentProps, changedProps, oldProps);\n\n      if ('value' in changedProps && this.__dispatchChange) {\n        this.dispatchEvent(new CustomEvent('change', { bubbles: true }));\n        this.__dispatchChange = false;\n      }\n    }\n\n    /**\n     * Opens the dropdown.\n     */\n    open() {\n      if (!this.disabled && !this.readonly) {\n        this.opened = true;\n      }\n    }\n\n    /**\n     * Closes the dropdown.\n     */\n    close() {\n      this.$.overlay.close();\n    }\n\n    /** @private */\n    _overlayRenderer(root) {\n      if (root.firstChild) {\n        return;\n      }\n\n      // Create and store document content element\n      const content = document.createElement('vaadin-date-picker-overlay-content');\n      root.appendChild(content);\n\n      this._overlayContent = content;\n\n      content.addEventListener('close', () => {\n        this._close();\n      });\n\n      content.addEventListener('focus-input', this._focusAndSelect.bind(this));\n\n      // User confirmed selected date by clicking the calendar.\n      content.addEventListener('date-tap', (e) => {\n        this.__userConfirmedDate = true;\n\n        this._selectDate(e.detail.date);\n\n        this._close();\n      });\n\n      // User confirmed selected date by pressing Enter, Space, or Today.\n      content.addEventListener('date-selected', (e) => {\n        // Reset if a date is deselected.\n        this.__userConfirmedDate = !!e.detail.date;\n\n        this._selectDate(e.detail.date);\n      });\n\n      // Set focus-ring attribute when moving focus to the overlay\n      // by pressing Tab or arrow key, after opening it on click.\n      content.addEventListener('focusin', () => {\n        if (this._keyboardActive) {\n          this._setFocused(true);\n        }\n      });\n\n      // Two-way data binding for `focusedDate` property\n      content.addEventListener('focused-date-changed', (e) => {\n        this._focusedDate = e.detail.value;\n      });\n    }\n\n    /**\n     * Returns true if the current input value satisfies all constraints (if any)\n     *\n     * Override the `checkValidity` method for custom validations.\n     *\n     * @return {boolean} True if the value is valid\n     */\n    checkValidity() {\n      const inputValue = this._inputElementValue;\n      const inputValid =\n        !inputValue ||\n        (!!this._selectedDate && inputValue === this._getFormattedDate(this.i18n.formatDate, this._selectedDate));\n      const minMaxValid = !this._selectedDate || dateAllowed(this._selectedDate, this._minDate, this._maxDate);\n\n      let inputValidity = true;\n      if (this.inputElement) {\n        if (this.inputElement.checkValidity) {\n          inputValidity = this.inputElement.checkValidity();\n        } else if (this.inputElement.validate) {\n          // Iron-form-elements have the validate API\n          inputValidity = this.inputElement.validate();\n        }\n      }\n\n      return inputValid && minMaxValid && inputValidity;\n    }\n\n    /**\n     * Override method inherited from `FocusMixin`\n     * to not call `_setFocused(true)` when focus\n     * is restored after closing overlay on click,\n     * and to avoid removing `focus-ring` attribute.\n     *\n     * @param {!FocusEvent} _event\n     * @return {boolean}\n     * @protected\n     * @override\n     */\n    _shouldSetFocus(_event) {\n      return !this._shouldKeepFocusRing;\n    }\n\n    /**\n     * Override method inherited from `FocusMixin`\n     * to prevent removing the `focused` attribute:\n     * - when moving focus to the overlay content,\n     * - when closing on date click / outside click.\n     *\n     * @param {!FocusEvent} _event\n     * @return {boolean}\n     * @protected\n     * @override\n     */\n    _shouldRemoveFocus(_event) {\n      return !this.opened;\n    }\n\n    /**\n     * Override method inherited from `FocusMixin`\n     * to store the `focus-ring` state to restore\n     * it later when closing on outside click.\n     *\n     * @param {boolean} focused\n     * @protected\n     * @override\n     */\n    _setFocused(focused) {\n      super._setFocused(focused);\n\n      this._shouldKeepFocusRing = focused && this._keyboardActive;\n    }\n\n    /**\n     * Select date on user interaction and set the flag\n     * to fire change event if necessary.\n     *\n     * @param {Date} dateToSelect\n     * @protected\n     */\n    _selectDate(dateToSelect) {\n      const value = this._formatISO(dateToSelect);\n\n      // Only set flag if the value will change.\n      if (this.value !== value) {\n        this.__dispatchChange = true;\n      }\n\n      this._selectedDate = dateToSelect;\n    }\n\n    /** @private */\n    _close() {\n      this._focus();\n      this.close();\n    }\n\n    /** @private */\n    __bringToFront() {\n      requestAnimationFrame(() => {\n        this.$.overlay.bringToFront();\n      });\n    }\n\n    /** @private */\n    // eslint-disable-next-line max-params\n    _isNoInput(inputElement, fullscreen, ios, i18n, opened, autoOpenDisabled) {\n      // On fullscreen mode, text input is disabled if auto-open isn't disabled or\n      // whenever the dropdown is opened\n      const noInputOnFullscreenMode = fullscreen && (!autoOpenDisabled || opened);\n      // On iOS, text input is disabled whenever the dropdown is opened, because\n      // the virtual keyboard doesn't affect the viewport metrics and thus the\n      // dropdown could get covered by the keyboard.\n      const noInputOnIos = ios && opened;\n\n      return !inputElement || noInputOnFullscreenMode || noInputOnIos || !i18n.parseDate;\n    }\n\n    /** @private */\n    _formatISO(date) {\n      if (!(date instanceof Date)) {\n        return '';\n      }\n\n      const pad = (num, fmt = '00') => (fmt + num).substr((fmt + num).length - fmt.length);\n\n      let yearSign = '';\n      let yearFmt = '0000';\n      let yearAbs = date.getFullYear();\n      if (yearAbs < 0) {\n        yearAbs = -yearAbs;\n        yearSign = '-';\n        yearFmt = '000000';\n      } else if (date.getFullYear() >= 10000) {\n        yearSign = '+';\n        yearFmt = '000000';\n      }\n\n      const year = yearSign + pad(yearAbs, yearFmt);\n      const month = pad(date.getMonth() + 1);\n      const day = pad(date.getDate());\n      return [year, month, day].join('-');\n    }\n\n    /** @protected */\n    _inputElementChanged(input) {\n      super._inputElementChanged(input);\n      if (input) {\n        input.autocomplete = 'off';\n        input.setAttribute('role', 'combobox');\n        input.setAttribute('aria-haspopup', 'dialog');\n        input.setAttribute('aria-expanded', !!this.opened);\n        this._applyInputValue(this._selectedDate);\n      }\n    }\n\n    /** @protected */\n    _openedChanged(opened) {\n      if (this.inputElement) {\n        this.inputElement.setAttribute('aria-expanded', opened);\n      }\n    }\n\n    /** @private */\n    _selectedDateChanged(selectedDate, formatDate) {\n      if (selectedDate === undefined || formatDate === undefined) {\n        return;\n      }\n      const value = this._formatISO(selectedDate);\n\n      if (!this.__keepInputValue) {\n        this._applyInputValue(selectedDate);\n      }\n\n      if (value !== this.value) {\n        this.validate();\n        this.value = value;\n      }\n      this._ignoreFocusedDateChange = true;\n      this._focusedDate = selectedDate;\n      this._ignoreFocusedDateChange = false;\n    }\n\n    /** @private */\n    _focusedDateChanged(focusedDate, formatDate) {\n      if (focusedDate === undefined || formatDate === undefined) {\n        return;\n      }\n      if (!this._ignoreFocusedDateChange && !this._noInput) {\n        this._applyInputValue(focusedDate);\n      }\n    }\n\n    /**\n     * Override the value observer from `InputMixin` to implement custom\n     * handling of the `value` property. The date-picker doesn't forward\n     * the value directly to the input like the default implementation of `InputMixin`.\n     * Instead, it parses the value into a date, puts it in `_selectedDate` which\n     * is then displayed in the input with respect to the specified date format.\n     *\n     * @param {string | undefined} value\n     * @param {string | undefined} oldValue\n     * @protected\n     * @override\n     */\n    _valueChanged(value, oldValue) {\n      const newDate = parseDate(value);\n\n      if (value && !newDate) {\n        // The new value cannot be parsed, revert the old value.\n        this.value = oldValue;\n        return;\n      }\n\n      if (value) {\n        if (!dateEquals(this._selectedDate, newDate)) {\n          // Update the date instance only if the date has actually changed.\n          this._selectedDate = newDate;\n\n          if (oldValue !== undefined) {\n            // Validate only if `value` changes after initialization.\n            this.validate();\n          }\n        }\n      } else {\n        this._selectedDate = null;\n      }\n\n      this._toggleHasValue(this._hasValue);\n    }\n\n    /** @private */\n    // eslint-disable-next-line max-params\n    __updateOverlayContent(overlayContent, i18n, label, minDate, maxDate, focusedDate, selectedDate, showWeekNumbers) {\n      if (overlayContent) {\n        overlayContent.setProperties({\n          i18n,\n          label,\n          minDate,\n          maxDate,\n          focusedDate,\n          selectedDate,\n          showWeekNumbers,\n        });\n      }\n    }\n\n    /** @private */\n    __updateOverlayContentTheme(overlayContent, theme) {\n      if (overlayContent) {\n        if (theme) {\n          overlayContent.setAttribute('theme', theme);\n        } else {\n          overlayContent.removeAttribute('theme');\n        }\n      }\n    }\n\n    /** @private */\n    __updateOverlayContentFullScreen(overlayContent, fullscreen) {\n      if (overlayContent) {\n        overlayContent.toggleAttribute('fullscreen', fullscreen);\n      }\n    }\n\n    /** @protected */\n    _onOverlayEscapePress() {\n      this._focusedDate = this._selectedDate;\n      this._close();\n    }\n\n    /** @protected */\n    _onOverlayOpened() {\n      const content = this._overlayContent;\n\n      // Detect which date to show\n      const initialPosition = this._getInitialPosition();\n      content.initialPosition = initialPosition;\n\n      // Scroll the date into view\n      const scrollFocusDate = content.focusedDate || initialPosition;\n      content.scrollToDate(scrollFocusDate);\n\n      // Ensure the date is focused\n      this._ignoreFocusedDateChange = true;\n      content.focusedDate = scrollFocusDate;\n      this._ignoreFocusedDateChange = false;\n\n      window.addEventListener('scroll', this._boundOnScroll, true);\n\n      if (this._focusOverlayOnOpen) {\n        content.focusDateElement();\n        this._focusOverlayOnOpen = false;\n      } else {\n        this._focus();\n      }\n\n      const input = this._nativeInput;\n      if (this._noInput && input) {\n        input.blur();\n        this._overlayContent.focusDateElement();\n      }\n\n      const focusables = this._noInput ? content : [input, content];\n      this.__showOthers = hideOthers(focusables);\n    }\n\n    /** @private */\n    _getInitialPosition() {\n      const parsedInitialPosition = parseDate(this.initialPosition);\n\n      const initialPosition =\n        this._selectedDate || this._overlayContent.initialPosition || parsedInitialPosition || new Date();\n\n      return parsedInitialPosition || dateAllowed(initialPosition, this._minDate, this._maxDate)\n        ? initialPosition\n        : getClosestDate(initialPosition, [this._minDate, this._maxDate]);\n    }\n\n    /** @private */\n    _selectParsedOrFocusedDate() {\n      // Select the parsed input or focused date\n      this._ignoreFocusedDateChange = true;\n      if (this.i18n.parseDate) {\n        const inputValue = this._inputElementValue || '';\n        const parsedDate = this._getParsedDate(inputValue);\n\n        if (this._isValidDate(parsedDate)) {\n          this._selectDate(parsedDate);\n        } else {\n          this.__keepInputValue = true;\n          this._selectDate(null);\n          this._selectedDate = null;\n          this.__keepInputValue = false;\n        }\n      } else if (this._focusedDate) {\n        this._selectDate(this._focusedDate);\n      }\n      this._ignoreFocusedDateChange = false;\n    }\n\n    /** @protected */\n    _onOverlayClosed() {\n      // Reset `aria-hidden` state.\n      if (this.__showOthers) {\n        this.__showOthers();\n        this.__showOthers = null;\n      }\n\n      window.removeEventListener('scroll', this._boundOnScroll, true);\n\n      // No need to select date on close if it was confirmed by the user.\n      if (this.__userConfirmedDate) {\n        this.__userConfirmedDate = false;\n      } else {\n        this._selectParsedOrFocusedDate();\n      }\n\n      if (this._nativeInput && this._nativeInput.selectionStart) {\n        this._nativeInput.selectionStart = this._nativeInput.selectionEnd;\n      }\n      // No need to revalidate the value after `_selectedDateChanged`\n      // Needed in case the value was not changed: open and close dropdown.\n      if (!this.value) {\n        this.validate();\n      }\n    }\n\n    /** @private */\n    _onScroll(e) {\n      if (e.target === window || !this._overlayContent.contains(e.target)) {\n        this._overlayContent._repositionYearScroller();\n      }\n    }\n\n    /** @protected */\n    _focus() {\n      if (!this._noInput) {\n        this.inputElement.focus();\n      }\n    }\n\n    /** @private */\n    _focusAndSelect() {\n      this._focus();\n      this._setSelectionRange(0, this._inputElementValue.length);\n    }\n\n    /** @private */\n    _applyInputValue(date) {\n      this._inputElementValue = date ? this._getFormattedDate(this.i18n.formatDate, date) : '';\n    }\n\n    /** @private */\n    _getFormattedDate(formatDate, date) {\n      return formatDate(extractDateParts(date));\n    }\n\n    /** @private */\n    _setSelectionRange(a, b) {\n      if (this._nativeInput && this._nativeInput.setSelectionRange) {\n        this._nativeInput.setSelectionRange(a, b);\n      }\n    }\n\n    /** @private */\n    _isValidDate(d) {\n      return d && !isNaN(d.getTime());\n    }\n\n    /**\n     * Override an event listener from `InputConstraintsMixin`\n     * to have date-picker fully control when to fire a change event.\n     * @protected\n     */\n    _onChange(event) {\n      // For change event on the native <input> blur, after the input is cleared,\n      // we schedule change event to be dispatched on date-picker blur.\n      if (this._inputElementValue === '') {\n        this.__dispatchChange = true;\n      }\n\n      event.stopPropagation();\n    }\n\n    /**\n     * @param {Event} event\n     * @private\n     */\n    _onClick(event) {\n      // Clear button click is handled in separate listener\n      // but bubbles to the host, so we need to ignore it.\n      if (!this._isClearButton(event)) {\n        this._onHostClick(event);\n      }\n    }\n\n    /**\n     * @param {Event} event\n     * @private\n     */\n    _onHostClick(event) {\n      if (!this.autoOpenDisabled || this._noInput) {\n        event.preventDefault();\n        this.open();\n      }\n    }\n\n    /**\n     * Override an event listener from `InputControlMixin`\n     * to validate and dispatch change on clear.\n     * @protected\n     */\n    _onClearButtonClick(event) {\n      event.preventDefault();\n      this._inputElementValue = '';\n      this.value = '';\n      this.validate();\n      this.dispatchEvent(new CustomEvent('change', { bubbles: true }));\n    }\n\n    /**\n     * Override an event listener from `KeyboardMixin`.\n     * @param {KeyboardEvent} e\n     * @protected\n     * @override\n     */\n    _onKeyDown(e) {\n      super._onKeyDown(e);\n\n      if (this._noInput) {\n        // The input element cannot be readonly as it would conflict with\n        // the required attribute. Both are not allowed on an input element.\n        // Therefore we prevent default on most keydown events.\n        const allowedKeys = [\n          9, // Tab\n        ];\n        if (allowedKeys.indexOf(e.keyCode) === -1) {\n          e.preventDefault();\n        }\n      }\n\n      switch (e.key) {\n        case 'ArrowDown':\n        case 'ArrowUp':\n          // Prevent scrolling the page with arrows\n          e.preventDefault();\n          if (this.opened) {\n            // The overlay can be opened with ctrl + option + shift in VoiceOver\n            // and without this logic, it won't be possible to focus the dialog opened this way.\n            this._overlayContent.focusDateElement();\n          } else {\n            this._focusOverlayOnOpen = true;\n            this.open();\n          }\n          break;\n        case 'Tab':\n          if (this.opened) {\n            e.preventDefault();\n            e.stopPropagation();\n            // Clear the selection range (remains visible on IE)\n            this._setSelectionRange(0, 0);\n            if (e.shiftKey) {\n              this._overlayContent.focusCancel();\n            } else {\n              this._overlayContent.focusDateElement();\n            }\n          }\n          break;\n        default:\n          break;\n      }\n    }\n\n    /**\n     * Override an event listener from `KeyboardMixin`.\n     *\n     * @param {!KeyboardEvent} _event\n     * @protected\n     * @override\n     */\n    _onEnter(_event) {\n      const oldValue = this.value;\n      if (this.opened) {\n        // Closing will implicitly select parsed or focused date\n        this.close();\n      } else {\n        this._selectParsedOrFocusedDate();\n      }\n      if (oldValue === this.value) {\n        this.validate();\n      }\n    }\n\n    /**\n     * Override an event listener from `KeyboardMixin`.\n     * Do not call `super` in order to override clear\n     * button logic defined in `InputControlMixin`.\n     *\n     * @param {!KeyboardEvent} event\n     * @protected\n     * @override\n     */\n    _onEscape(event) {\n      // Closing overlay is handled in vaadin-overlay-escape-press event listener.\n      if (this.opened) {\n        return;\n      }\n\n      if (this.clearButtonVisible && !!this.value) {\n        // Stop event from propagating to the host element\n        // to avoid closing dialog when clearing on Esc\n        event.stopPropagation();\n        this._onClearButtonClick(event);\n        return;\n      }\n\n      if (this.autoOpenDisabled) {\n        // Do not restore selected date if Esc was pressed after clearing input field\n        if (this.inputElement.value === '') {\n          this._selectDate(null);\n        }\n        this._applyInputValue(this._selectedDate);\n      } else {\n        this._focusedDate = this._selectedDate;\n        this._selectParsedOrFocusedDate();\n      }\n    }\n\n    /** @private */\n    _getParsedDate(inputValue = this._inputElementValue) {\n      const dateObject = this.i18n.parseDate && this.i18n.parseDate(inputValue);\n      const parsedDate = dateObject && parseDate(`${dateObject.year}-${dateObject.month + 1}-${dateObject.day}`);\n      return parsedDate;\n    }\n\n    /** @protected */\n    _isClearButton(event) {\n      return event.composedPath()[0] === this.clearElement;\n    }\n\n    /**\n     * Override an event listener from `InputMixin`\n     * @protected\n     */\n    _onInput() {\n      if (!this.opened && this.inputElement.value && !this.autoOpenDisabled) {\n        this.open();\n      }\n      this._userInputValueChanged();\n    }\n\n    /** @private */\n    _userInputValueChanged() {\n      if (this._inputElementValue) {\n        const parsedDate = this._getParsedDate();\n\n        if (this._isValidDate(parsedDate)) {\n          this._ignoreFocusedDateChange = true;\n          if (!dateEquals(parsedDate, this._focusedDate)) {\n            this._focusedDate = parsedDate;\n          }\n          this._ignoreFocusedDateChange = false;\n        }\n      }\n    }\n\n    /** @private */\n    __computeMinOrMaxDate(dateString) {\n      return parseDate(dateString);\n    }\n\n    /**\n     * Fired when the user commits a value change.\n     *\n     * @event change\n     */\n\n    /**\n     * Fired when `value` property value changes.\n     *\n     * @event value-changed\n     */\n\n    /**\n     * Fired when `opened` property value changes.\n     *\n     * @event opened-changed\n     */\n  };\n","/**\n * @license\n * Copyright (c) 2016 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '@vaadin/input-container/src/vaadin-input-container.js';\nimport './vaadin-date-picker-overlay.js';\nimport './vaadin-date-picker-overlay-content.js';\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { ElementMixin } from '@vaadin/component-base/src/element-mixin.js';\nimport { TooltipController } from '@vaadin/component-base/src/tooltip-controller.js';\nimport { InputControlMixin } from '@vaadin/field-base/src/input-control-mixin.js';\nimport { InputController } from '@vaadin/field-base/src/input-controller.js';\nimport { LabelledInputController } from '@vaadin/field-base/src/labelled-input-controller.js';\nimport { inputFieldShared } from '@vaadin/field-base/src/styles/input-field-shared-styles.js';\nimport { registerStyles, ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { DatePickerMixin } from './vaadin-date-picker-mixin.js';\n\nregisterStyles('vaadin-date-picker', inputFieldShared, { moduleId: 'vaadin-date-picker-styles' });\n\n/**\n * `<vaadin-date-picker>` is an input field that allows to enter a date by typing or by selecting from a calendar overlay.\n *\n * ```html\n * <vaadin-date-picker label=\"Birthday\"></vaadin-date-picker>\n * ```\n *\n * ```js\n * datePicker.value = '2016-03-02';\n * ```\n *\n * When the selected `value` is changed, a `value-changed` event is triggered.\n *\n * ### Styling\n *\n * The following custom properties are available for styling:\n *\n * Custom property                | Description                | Default\n * -------------------------------|----------------------------|---------\n * `--vaadin-field-default-width` | Default width of the field | `12em`\n *\n * `<vaadin-date-picker>` provides the same set of shadow DOM parts and state attributes as `<vaadin-text-field>`.\n * See [`<vaadin-text-field>`](#/elements/vaadin-text-field) for the styling documentation.\n *\n * In addition to `<vaadin-text-field>` parts, the following parts are available for theming:\n *\n * Part name             | Description\n * ----------------------|--------------------\n * `toggle-button`       | Toggle button\n *\n * In addition to `<vaadin-text-field>` state attributes, the following state attributes are available for theming:\n *\n * Attribute  | Description                                      | Part name\n * -----------|--------------------------------------------------|-----------\n * `opened`   | Set when the date selector overlay is opened     | :host\n *\n * If you want to replace the default `<input>` and its container with a custom implementation to get full control\n * over the input field, consider using the [`<vaadin-date-picker-light>`](#/elements/vaadin-date-picker-light) element.\n *\n * ### Internal components\n *\n * In addition to `<vaadin-date-picker>` itself, the following internal\n * components are themable:\n *\n * - `<vaadin-date-picker-overlay>` - has the same API as [`<vaadin-overlay>`](#/elements/vaadin-overlay).\n * - `<vaadin-date-picker-overlay-content>`\n * - `<vaadin-date-picker-month-scroller>`\n * - `<vaadin-date-picker-year-scroller>`\n * - `<vaadin-date-picker-year>`\n * - `<vaadin-month-calendar>`\n * - [`<vaadin-input-container>`](#/elements/vaadin-input-container) - an internal element wrapping the input.\n *\n * In order to style the overlay content, use `<vaadin-date-picker-overlay-content>` shadow DOM parts:\n *\n * Part name             | Description\n * ----------------------|--------------------\n * `overlay-header`      | Fullscreen mode header\n * `label`               | Fullscreen mode value/label\n * `clear-button`        | Fullscreen mode clear button\n * `toggle-button`       | Fullscreen mode toggle button\n * `years-toggle-button` | Fullscreen mode years scroller toggle\n * `toolbar`             | Footer bar with slotted buttons\n *\n * The following state attributes are available on the `<vaadin-date-picker-overlay-content>` element:\n *\n * Attribute       | Description\n * ----------------|-------------------------------------------------\n * `desktop`       | Set when the overlay content is in desktop mode\n * `fullscreen`    | Set when the overlay content is in fullscreen mode\n * `years-visible` | Set when the year scroller is visible in fullscreen mode\n *\n * In order to style the month calendar, use `<vaadin-month-calendar>` shadow DOM parts:\n *\n * Part name             | Description\n * ----------------------|--------------------\n * `month-header`        | Month title\n * `weekdays`            | Weekday container\n * `weekday`             | Weekday element\n * `week-numbers`        | Week numbers container\n * `week-number`         | Week number element\n * `date`                | Date element\n * `disabled`            | Disabled date element\n * `focused`             | Focused date element\n * `selected`            | Selected date element\n * `today`               | Date element corresponding to the current day\n *\n * In order to style year scroller elements, use `<vaadin-date-picker-year>` shadow DOM parts:\n *\n * Part name             | Description\n * ----------------------|--------------------\n * `year-number`         | Year number\n * `year-separator`      | Year separator\n *\n * Note: the `theme` attribute value set on `<vaadin-date-picker>` is\n * propagated to the internal components listed above.\n *\n * See [Styling Components](https://vaadin.com/docs/latest/styling/styling-components) documentation.\n *\n * @fires {Event} change - Fired when the user commits a value change.\n * @fires {CustomEvent} invalid-changed - Fired when the `invalid` property changes.\n * @fires {CustomEvent} opened-changed - Fired when the `opened` property changes.\n * @fires {CustomEvent} value-changed - Fired when the `value` property changes.\n * @fires {CustomEvent} validated - Fired whenever the field is validated.\n *\n * @extends HTMLElement\n * @mixes ElementMixin\n * @mixes ThemableMixin\n * @mixes InputControlMixin\n * @mixes DatePickerMixin\n */\nclass DatePicker extends DatePickerMixin(InputControlMixin(ThemableMixin(ElementMixin(PolymerElement)))) {\n  static get is() {\n    return 'vaadin-date-picker';\n  }\n\n  static get template() {\n    return html`\n      <style>\n        :host([opened]) {\n          pointer-events: auto;\n        }\n\n        :host([dir='rtl']) [part='input-field'] {\n          direction: ltr;\n        }\n\n        :host([dir='rtl']) [part='input-field'] ::slotted(input)::placeholder {\n          direction: rtl;\n          text-align: left;\n        }\n      </style>\n\n      <div class=\"vaadin-date-picker-container\">\n        <div part=\"label\">\n          <slot name=\"label\"></slot>\n          <span part=\"required-indicator\" aria-hidden=\"true\" on-click=\"focus\"></span>\n        </div>\n\n        <vaadin-input-container\n          part=\"input-field\"\n          readonly=\"[[readonly]]\"\n          disabled=\"[[disabled]]\"\n          invalid=\"[[invalid]]\"\n          theme$=\"[[_theme]]\"\n        >\n          <slot name=\"prefix\" slot=\"prefix\"></slot>\n          <slot name=\"input\"></slot>\n          <div id=\"clearButton\" part=\"clear-button\" slot=\"suffix\" aria-hidden=\"true\"></div>\n          <div part=\"toggle-button\" slot=\"suffix\" aria-hidden=\"true\" on-click=\"_toggle\"></div>\n        </vaadin-input-container>\n\n        <div part=\"helper-text\">\n          <slot name=\"helper\"></slot>\n        </div>\n\n        <div part=\"error-message\">\n          <slot name=\"error-message\"></slot>\n        </div>\n      </div>\n\n      <vaadin-date-picker-overlay\n        id=\"overlay\"\n        fullscreen$=\"[[_fullscreen]]\"\n        theme$=\"[[_theme]]\"\n        opened=\"{{opened}}\"\n        on-vaadin-overlay-escape-press=\"_onOverlayEscapePress\"\n        on-vaadin-overlay-open=\"_onOverlayOpened\"\n        on-vaadin-overlay-closing=\"_onOverlayClosed\"\n        restore-focus-on-close\n        restore-focus-node=\"[[inputElement]]\"\n      ></vaadin-date-picker-overlay>\n\n      <slot name=\"tooltip\"></slot>\n    `;\n  }\n\n  /**\n   * Used by `InputControlMixin` as a reference to the clear button element.\n   * @protected\n   * @return {!HTMLElement}\n   */\n  get clearElement() {\n    return this.$.clearButton;\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n\n    this.addController(\n      new InputController(this, (input) => {\n        this._setInputElement(input);\n        this._setFocusElement(input);\n        this.stateTarget = input;\n        this.ariaTarget = input;\n      }),\n    );\n    this.addController(new LabelledInputController(this.inputElement, this._labelController));\n\n    this._tooltipController = new TooltipController(this);\n    this.addController(this._tooltipController);\n    this._tooltipController.setPosition('top');\n    this._tooltipController.setShouldShow((target) => !target.opened);\n\n    const toggleButton = this.shadowRoot.querySelector('[part=\"toggle-button\"]');\n    toggleButton.addEventListener('mousedown', (e) => e.preventDefault());\n\n    this.$.overlay.addEventListener('vaadin-overlay-close', this._onVaadinOverlayClose.bind(this));\n  }\n\n  /** @private */\n  _onVaadinOverlayClose(e) {\n    if (e.detail.sourceEvent && e.detail.sourceEvent.composedPath().includes(this)) {\n      e.preventDefault();\n    }\n  }\n\n  /** @private */\n  _toggle(e) {\n    e.stopPropagation();\n    if (this.$.overlay.opened) {\n      this.close();\n    } else {\n      this.open();\n    }\n  }\n\n  // Workaround https://github.com/vaadin/web-components/issues/2855\n  /** @protected */\n  _openedChanged(opened) {\n    super._openedChanged(opened);\n\n    this.$.overlay.positionTarget = this.shadowRoot.querySelector('[part=\"input-field\"]');\n    this.$.overlay.noVerticalOverlap = true;\n  }\n}\n\ncustomElements.define(DatePicker.is, DatePicker);\n\nexport { DatePicker };\n","import '@vaadin/vaadin-lumo-styles/font-icons.js';\nimport '@vaadin/vaadin-lumo-styles/sizing.js';\nimport '@vaadin/vaadin-lumo-styles/spacing.js';\nimport '@vaadin/vaadin-lumo-styles/style.js';\nimport '@vaadin/vaadin-lumo-styles/typography.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst item = css`\n  :host {\n    display: flex;\n    align-items: center;\n    box-sizing: border-box;\n    font-family: var(--lumo-font-family);\n    font-size: var(--lumo-font-size-m);\n    line-height: var(--lumo-line-height-xs);\n    padding: 0.5em calc(var(--lumo-space-l) + var(--lumo-border-radius-m) / 4) 0.5em\n      var(--_lumo-list-box-item-padding-left, calc(var(--lumo-border-radius-m) / 4));\n    min-height: var(--lumo-size-m);\n    outline: none;\n    border-radius: var(--lumo-border-radius-m);\n    cursor: var(--lumo-clickable-cursor);\n    -webkit-font-smoothing: antialiased;\n    -moz-osx-font-smoothing: grayscale;\n    -webkit-tap-highlight-color: var(--lumo-primary-color-10pct);\n  }\n\n  /* Checkmark */\n  [part='checkmark']::before {\n    display: var(--_lumo-item-selected-icon-display, none);\n    content: var(--lumo-icons-checkmark);\n    font-family: lumo-icons;\n    font-size: var(--lumo-icon-size-m);\n    line-height: 1;\n    font-weight: normal;\n    width: 1em;\n    height: 1em;\n    margin: calc((1 - var(--lumo-line-height-xs)) * var(--lumo-font-size-m) / 2) 0;\n    color: var(--lumo-primary-text-color);\n    flex: none;\n    opacity: 0;\n    transition: transform 0.2s cubic-bezier(0.12, 0.32, 0.54, 2), opacity 0.1s;\n  }\n\n  :host([selected]) [part='checkmark']::before {\n    opacity: 1;\n  }\n\n  :host([active]:not([selected])) [part='checkmark']::before {\n    transform: scale(0.8);\n    opacity: 0;\n    transition-duration: 0s;\n  }\n\n  [part='content'] {\n    flex: auto;\n  }\n\n  /* Disabled */\n  :host([disabled]) {\n    color: var(--lumo-disabled-text-color);\n    cursor: default;\n    pointer-events: none;\n  }\n\n  /* TODO a workaround until we have \"focus-follows-mouse\". After that, use the hover style for focus-ring as well */\n  @media (any-hover: hover) {\n    :host(:hover:not([disabled])) {\n      background-color: var(--lumo-primary-color-10pct);\n    }\n\n    :host([focus-ring]:not([disabled])) {\n      box-shadow: inset 0 0 0 2px var(--lumo-primary-color-50pct);\n    }\n  }\n\n  /* RTL specific styles */\n  :host([dir='rtl']) {\n    padding-left: calc(var(--lumo-space-l) + var(--lumo-border-radius-m) / 4);\n    padding-right: var(--_lumo-list-box-item-padding-left, calc(var(--lumo-border-radius-m) / 4));\n  }\n\n  /* Slotted icons */\n  :host ::slotted(vaadin-icon) {\n    width: var(--lumo-icon-size-m);\n    height: var(--lumo-icon-size-m);\n  }\n`;\n\nregisterStyles('vaadin-item', item, { moduleId: 'lumo-item' });\n\nexport { item };\n","import '@vaadin/vaadin-lumo-styles/color.js';\nimport '@vaadin/vaadin-lumo-styles/spacing.js';\nimport '@vaadin/vaadin-lumo-styles/style.js';\nimport { item } from '@vaadin/item/theme/lumo/vaadin-item-styles.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst comboBoxItem = css`\n  :host {\n    transition: background-color 100ms;\n    overflow: hidden;\n    --_lumo-item-selected-icon-display: block;\n  }\n\n  @media (any-hover: hover) {\n    :host([focused]:not([disabled])) {\n      box-shadow: inset 0 0 0 2px var(--lumo-primary-color-50pct);\n    }\n  }\n`;\n\nregisterStyles('vaadin-combo-box-item', [item, comboBoxItem], {\n  moduleId: 'lumo-combo-box-item',\n});\n\nexport { comboBoxItem };\n","/**\n * @license\n * Copyright (c) 2022 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '../color.js';\nimport '../sizing.js';\nimport { css } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst loader = css`\n  [part~='loader'] {\n    box-sizing: border-box;\n    width: var(--lumo-icon-size-s);\n    height: var(--lumo-icon-size-s);\n    border: 2px solid transparent;\n    border-color: var(--lumo-primary-color-10pct) var(--lumo-primary-color-10pct) var(--lumo-primary-color)\n      var(--lumo-primary-color);\n    border-radius: calc(0.5 * var(--lumo-icon-size-s));\n    opacity: 0;\n    pointer-events: none;\n  }\n\n  :host(:not([loading])) [part~='loader'] {\n    display: none;\n  }\n\n  :host([loading]) [part~='loader'] {\n    animation: 1s linear infinite lumo-loader-rotate, 0.3s 0.1s lumo-loader-fade-in both;\n  }\n\n  @keyframes lumo-loader-fade-in {\n    0% {\n      opacity: 0;\n    }\n\n    100% {\n      opacity: 1;\n    }\n  }\n\n  @keyframes lumo-loader-rotate {\n    0% {\n      transform: rotate(0deg);\n    }\n\n    100% {\n      transform: rotate(360deg);\n    }\n  }\n`;\n\nexport { loader };\n","import '@vaadin/vaadin-lumo-styles/color.js';\nimport '@vaadin/vaadin-lumo-styles/spacing.js';\nimport '@vaadin/vaadin-lumo-styles/style.js';\nimport '@vaadin/overlay/theme/lumo/vaadin-overlay.js';\nimport { loader } from '@vaadin/vaadin-lumo-styles/mixins/loader.js';\nimport { menuOverlayCore } from '@vaadin/vaadin-lumo-styles/mixins/menu-overlay.js';\nimport { overlay } from '@vaadin/vaadin-lumo-styles/mixins/overlay.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst comboBoxOverlay = css`\n  [part='content'] {\n    padding: 0;\n  }\n\n  /* When items are empty, the spinner needs some room */\n  :host(:not([closing])) [part~='content'] {\n    min-height: calc(2 * var(--lumo-space-s) + var(--lumo-icon-size-s));\n  }\n\n  [part~='overlay'] {\n    position: relative;\n  }\n\n  :host([top-aligned]) [part~='overlay'] {\n    margin-top: var(--lumo-space-xs);\n  }\n\n  :host([bottom-aligned]) [part~='overlay'] {\n    margin-bottom: var(--lumo-space-xs);\n  }\n`;\n\nconst comboBoxLoader = css`\n  [part~='loader'] {\n    position: absolute;\n    z-index: 1;\n    left: var(--lumo-space-s);\n    right: var(--lumo-space-s);\n    top: var(--lumo-space-s);\n    margin-left: auto;\n    margin-inline-start: auto;\n    margin-inline-end: 0;\n  }\n\n  :host([dir='rtl']) [part~='loader'] {\n    left: auto;\n    margin-left: 0;\n    margin-right: auto;\n    margin-inline-start: 0;\n    margin-inline-end: auto;\n  }\n`;\n\nregisterStyles(\n  'vaadin-combo-box-overlay',\n  [\n    overlay,\n    menuOverlayCore,\n    comboBoxOverlay,\n    loader,\n    comboBoxLoader,\n    css`\n      :host {\n        --_vaadin-combo-box-items-container-border-width: var(--lumo-space-xs);\n        --_vaadin-combo-box-items-container-border-style: solid;\n      }\n    `,\n  ],\n  { moduleId: 'lumo-combo-box-overlay' },\n);\n\nexport { comboBoxLoader, comboBoxOverlay };\n","/**\n * @license\n * Copyright (c) 2018 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '@vaadin/vaadin-lumo-styles/font-icons.js';\nimport { comboBoxItem } from '@vaadin/combo-box/theme/lumo/vaadin-combo-box-item-styles.js';\nimport { comboBoxOverlay } from '@vaadin/combo-box/theme/lumo/vaadin-combo-box-overlay-styles.js';\nimport { item } from '@vaadin/item/theme/lumo/vaadin-item-styles.js';\nimport { inputFieldShared } from '@vaadin/vaadin-lumo-styles/mixins/input-field-shared.js';\nimport { menuOverlayCore } from '@vaadin/vaadin-lumo-styles/mixins/menu-overlay.js';\nimport { overlay } from '@vaadin/vaadin-lumo-styles/mixins/overlay.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles('vaadin-time-picker-item', [item, comboBoxItem], {\n  moduleId: 'lumo-time-picker-item',\n});\n\nregisterStyles(\n  'vaadin-time-picker-overlay',\n  [\n    overlay,\n    menuOverlayCore,\n    comboBoxOverlay,\n    css`\n      :host {\n        --_vaadin-time-picker-items-container-border-width: var(--lumo-space-xs);\n        --_vaadin-time-picker-items-container-border-style: solid;\n      }\n    `,\n  ],\n  {\n    moduleId: 'lumo-time-picker-overlay',\n  },\n);\n\nconst timePicker = css`\n  [part~='toggle-button']::before {\n    content: var(--lumo-icons-clock);\n  }\n\n  :host([dir='rtl']) [part='input-field'] ::slotted(input:placeholder-shown) {\n    --_lumo-text-field-overflow-mask-image: none;\n  }\n\n  :host([dir='rtl']) [part='input-field'] ::slotted(input) {\n    --_lumo-text-field-overflow-mask-image: linear-gradient(to left, transparent, #000 1.25em);\n  }\n`;\n\nregisterStyles('vaadin-time-picker', [inputFieldShared, timePicker], { moduleId: 'lumo-time-picker' });\n","/**\n * @license\n * Copyright (c) 2015 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/**\n * @polymerMixin\n */\nexport const ComboBoxItemMixin = (superClass) =>\n  class ComboBoxItemMixinClass extends superClass {\n    static get properties() {\n      return {\n        /**\n         * The index of the item.\n         */\n        index: {\n          type: Number,\n        },\n\n        /**\n         * The item to render.\n         */\n        item: {\n          type: Object,\n        },\n\n        /**\n         * The text to render in the item.\n         */\n        label: {\n          type: String,\n        },\n\n        /**\n         * True when item is selected.\n         */\n        selected: {\n          type: Boolean,\n          value: false,\n          reflectToAttribute: true,\n        },\n\n        /**\n         * True when item is focused.\n         */\n        focused: {\n          type: Boolean,\n          value: false,\n          reflectToAttribute: true,\n        },\n\n        /**\n         * Custom function for rendering the item content.\n         */\n        renderer: {\n          type: Function,\n        },\n      };\n    }\n\n    static get observers() {\n      return ['__rendererOrItemChanged(renderer, index, item.*, selected, focused)', '__updateLabel(label, renderer)'];\n    }\n\n    /** @protected */\n    connectedCallback() {\n      super.connectedCallback();\n\n      this._owner = this.parentNode.owner;\n\n      const hostDir = this._owner.getAttribute('dir');\n      if (hostDir) {\n        this.setAttribute('dir', hostDir);\n      }\n    }\n\n    /**\n     * Requests an update for the content of the item.\n     * While performing the update, it invokes the renderer passed in the `renderer` property.\n     *\n     * It is not guaranteed that the update happens immediately (synchronously) after it is requested.\n     */\n    requestContentUpdate() {\n      if (!this.renderer) {\n        return;\n      }\n\n      const model = {\n        index: this.index,\n        item: this.item,\n        focused: this.focused,\n        selected: this.selected,\n      };\n\n      this.renderer(this, this._owner, model);\n    }\n\n    /** @private */\n    __rendererOrItemChanged(renderer, index, item) {\n      if (item === undefined || index === undefined) {\n        return;\n      }\n\n      if (this._oldRenderer !== renderer) {\n        this.innerHTML = '';\n        // Whenever a Lit-based renderer is used, it assigns a Lit part to the node it was rendered into.\n        // When clearing the rendered content, this part needs to be manually disposed of.\n        // Otherwise, using a Lit-based renderer on the same node will throw an exception or render nothing afterward.\n        delete this._$litPart$;\n      }\n\n      if (renderer) {\n        this._oldRenderer = renderer;\n        this.requestContentUpdate();\n      }\n    }\n\n    /** @private */\n    __updateLabel(label, renderer) {\n      if (renderer) {\n        return;\n      }\n\n      this.textContent = label;\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2018 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { ComboBoxItemMixin } from '@vaadin/combo-box/src/vaadin-combo-box-item-mixin.js';\nimport { DirMixin } from '@vaadin/component-base/src/dir-mixin.js';\nimport { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\n/**\n * An item element used by the `<vaadin-time-picker>` dropdown.\n *\n * ### Styling\n *\n * The following shadow DOM parts are available for styling:\n *\n * Part name   | Description\n * ------------|--------------\n * `checkmark` | The graphical checkmark shown for a selected item\n * `content`   | The element that wraps the item content\n *\n * The following state attributes are exposed for styling:\n *\n * Attribute    | Description\n * -------------|-------------\n * `selected`   | Set when the item is selected\n * `focused`    | Set when the item is focused\n *\n * See [Styling Components](https://vaadin.com/docs/latest/styling/styling-components) documentation.\n *\n * @mixes ComboBoxItemMixin\n * @mixes ThemableMixin\n * @mixes DirMixin\n * @private\n */\nexport class TimePickerItem extends ComboBoxItemMixin(ThemableMixin(DirMixin(PolymerElement))) {\n  static get is() {\n    return 'vaadin-time-picker-item';\n  }\n\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: block;\n        }\n\n        :host([hidden]) {\n          display: none !important;\n        }\n      </style>\n      <span part=\"checkmark\" aria-hidden=\"true\"></span>\n      <div part=\"content\">\n        <slot></slot>\n      </div>\n    `;\n  }\n}\n\ncustomElements.define(TimePickerItem.is, TimePickerItem);\n","/**\n * @license\n * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt\n */\nimport { animationFrame, idlePeriod, microTask } from './async.js';\nimport { Debouncer, enqueueDebouncer, flush } from './debounce.js';\n\nconst IOS = navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\\d+)/u);\nconst IOS_TOUCH_SCROLLING = IOS && IOS[1] >= 8;\nconst DEFAULT_PHYSICAL_COUNT = 3;\n\n/**\n * DO NOT EDIT THIS FILE!\n *\n * This file includes the iron-list scrolling engine copied from\n * https://github.com/PolymerElements/iron-list/blob/master/iron-list.js\n *\n * If something in the scrolling engine needs to be changed\n * for the virtualizer's purposes, override a function\n * in virtualizer-iron-list-adapter.js instead of changing it here.\n * If a function on this file is no longer needed, the code can be safely deleted.\n *\n * This will allow us to keep the iron-list code here as close to\n * the original as possible.\n */\nexport const ironList = {\n  /**\n   * The ratio of hidden tiles that should remain in the scroll direction.\n   * Recommended value ~0.5, so it will distribute tiles evenly in both\n   * directions.\n   */\n  _ratio: 0.5,\n\n  /**\n   * The padding-top value for the list.\n   */\n  _scrollerPaddingTop: 0,\n\n  /**\n   * This value is a cached value of `scrollTop` from the last `scroll` event.\n   */\n  _scrollPosition: 0,\n\n  /**\n   * The sum of the heights of all the tiles in the DOM.\n   */\n  _physicalSize: 0,\n\n  /**\n   * The average `offsetHeight` of the tiles observed till now.\n   */\n  _physicalAverage: 0,\n\n  /**\n   * The number of tiles which `offsetHeight` > 0 observed until now.\n   */\n  _physicalAverageCount: 0,\n\n  /**\n   * The Y position of the item rendered in the `_physicalStart`\n   * tile relative to the scrolling list.\n   */\n  _physicalTop: 0,\n\n  /**\n   * The number of items in the list.\n   */\n  _virtualCount: 0,\n\n  /**\n   * The estimated scroll height based on `_physicalAverage`\n   */\n  _estScrollHeight: 0,\n\n  /**\n   * The scroll height of the dom node\n   */\n  _scrollHeight: 0,\n\n  /**\n   * The height of the list. This is referred as the viewport in the context of\n   * list.\n   */\n  _viewportHeight: 0,\n\n  /**\n   * The width of the list. This is referred as the viewport in the context of\n   * list.\n   */\n  _viewportWidth: 0,\n\n  /**\n   * An array of DOM nodes that are currently in the tree\n   * @type {?Array<!HTMLElement>}\n   */\n  _physicalItems: null,\n\n  /**\n   * An array of heights for each item in `_physicalItems`\n   * @type {?Array<number>}\n   */\n  _physicalSizes: null,\n\n  /**\n   * A cached value for the first visible index.\n   * See `firstVisibleIndex`\n   * @type {?number}\n   */\n  _firstVisibleIndexVal: null,\n\n  /**\n   * A cached value for the last visible index.\n   * See `lastVisibleIndex`\n   * @type {?number}\n   */\n  _lastVisibleIndexVal: null,\n\n  /**\n   * The max number of pages to render. One page is equivalent to the height of\n   * the list.\n   */\n  _maxPages: 2,\n\n  /**\n   * The cost of stamping a template in ms.\n   */\n  _templateCost: 0,\n\n  /**\n   * The bottom of the physical content.\n   */\n  get _physicalBottom() {\n    return this._physicalTop + this._physicalSize;\n  },\n\n  /**\n   * The bottom of the scroll.\n   */\n  get _scrollBottom() {\n    return this._scrollPosition + this._viewportHeight;\n  },\n\n  /**\n   * The n-th item rendered in the last physical item.\n   */\n  get _virtualEnd() {\n    return this._virtualStart + this._physicalCount - 1;\n  },\n\n  /**\n   * The height of the physical content that isn't on the screen.\n   */\n  get _hiddenContentSize() {\n    return this._physicalSize - this._viewportHeight;\n  },\n\n  /**\n   * The maximum scroll top value.\n   */\n  get _maxScrollTop() {\n    return this._estScrollHeight - this._viewportHeight + this._scrollOffset;\n  },\n\n  /**\n   * The largest n-th value for an item such that it can be rendered in\n   * `_physicalStart`.\n   */\n  get _maxVirtualStart() {\n    const virtualCount = this._virtualCount;\n    return Math.max(0, virtualCount - this._physicalCount);\n  },\n\n  get _virtualStart() {\n    return this._virtualStartVal || 0;\n  },\n\n  set _virtualStart(val) {\n    val = this._clamp(val, 0, this._maxVirtualStart);\n    this._virtualStartVal = val;\n  },\n\n  get _physicalStart() {\n    return this._physicalStartVal || 0;\n  },\n\n  /**\n   * The k-th tile that is at the top of the scrolling list.\n   */\n  set _physicalStart(val) {\n    val %= this._physicalCount;\n    if (val < 0) {\n      val = this._physicalCount + val;\n    }\n    this._physicalStartVal = val;\n  },\n\n  /**\n   * The k-th tile that is at the bottom of the scrolling list.\n   */\n  get _physicalEnd() {\n    return (this._physicalStart + this._physicalCount - 1) % this._physicalCount;\n  },\n\n  get _physicalCount() {\n    return this._physicalCountVal || 0;\n  },\n\n  set _physicalCount(val) {\n    this._physicalCountVal = val;\n  },\n\n  /**\n   * An optimal physical size such that we will have enough physical items\n   * to fill up the viewport and recycle when the user scrolls.\n   *\n   * This default value assumes that we will at least have the equivalent\n   * to a viewport of physical items above and below the user's viewport.\n   */\n  get _optPhysicalSize() {\n    return this._viewportHeight === 0 ? Infinity : this._viewportHeight * this._maxPages;\n  },\n\n  /**\n   * True if the current list is visible.\n   */\n  get _isVisible() {\n    return Boolean(this.offsetWidth || this.offsetHeight);\n  },\n\n  /**\n   * Gets the index of the first visible item in the viewport.\n   *\n   * @type {number}\n   */\n  get firstVisibleIndex() {\n    let idx = this._firstVisibleIndexVal;\n    if (idx == null) {\n      let physicalOffset = this._physicalTop + this._scrollOffset;\n\n      idx =\n        this._iterateItems((pidx, vidx) => {\n          physicalOffset += this._getPhysicalSizeIncrement(pidx);\n\n          if (physicalOffset > this._scrollPosition) {\n            return vidx;\n          }\n        }) || 0;\n      this._firstVisibleIndexVal = idx;\n    }\n    return idx;\n  },\n\n  /**\n   * Gets the index of the last visible item in the viewport.\n   *\n   * @type {number}\n   */\n  get lastVisibleIndex() {\n    let idx = this._lastVisibleIndexVal;\n    if (idx == null) {\n      let physicalOffset = this._physicalTop + this._scrollOffset;\n      this._iterateItems((pidx, vidx) => {\n        if (physicalOffset < this._scrollBottom) {\n          idx = vidx;\n        }\n        physicalOffset += this._getPhysicalSizeIncrement(pidx);\n      });\n\n      this._lastVisibleIndexVal = idx;\n    }\n    return idx;\n  },\n\n  get _scrollOffset() {\n    return this._scrollerPaddingTop + this.scrollOffset;\n  },\n\n  /**\n   * Recycles the physical items when needed.\n   */\n  _scrollHandler() {\n    const scrollTop = Math.max(0, Math.min(this._maxScrollTop, this._scrollTop));\n    let delta = scrollTop - this._scrollPosition;\n    const isScrollingDown = delta >= 0;\n    // Track the current scroll position.\n    this._scrollPosition = scrollTop;\n    // Clear indexes for first and last visible indexes.\n    this._firstVisibleIndexVal = null;\n    this._lastVisibleIndexVal = null;\n    // Random access.\n    if (Math.abs(delta) > this._physicalSize && this._physicalSize > 0) {\n      delta -= this._scrollOffset;\n      const idxAdjustment = Math.round(delta / this._physicalAverage);\n      this._virtualStart += idxAdjustment;\n      this._physicalStart += idxAdjustment;\n      // Estimate new physical offset based on the virtual start index.\n      // adjusts the physical start position to stay in sync with the clamped\n      // virtual start index. It's critical not to let this value be\n      // more than the scroll position however, since that would result in\n      // the physical items not covering the viewport, and leading to\n      // _increasePoolIfNeeded to run away creating items to try to fill it.\n      this._physicalTop = Math.min(Math.floor(this._virtualStart) * this._physicalAverage, this._scrollPosition);\n      this._update();\n    } else if (this._physicalCount > 0) {\n      const reusables = this._getReusables(isScrollingDown);\n      if (isScrollingDown) {\n        this._physicalTop = reusables.physicalTop;\n        this._virtualStart += reusables.indexes.length;\n        this._physicalStart += reusables.indexes.length;\n      } else {\n        this._virtualStart -= reusables.indexes.length;\n        this._physicalStart -= reusables.indexes.length;\n      }\n      this._update(reusables.indexes, isScrollingDown ? null : reusables.indexes);\n      this._debounce('_increasePoolIfNeeded', this._increasePoolIfNeeded.bind(this, 0), microTask);\n    }\n  },\n\n  /**\n   * Returns an object that contains the indexes of the physical items\n   * that might be reused and the physicalTop.\n   *\n   * @param {boolean} fromTop If the potential reusable items are above the scrolling region.\n   */\n  _getReusables(fromTop) {\n    let ith, offsetContent, physicalItemHeight;\n    const idxs = [];\n    const protectedOffsetContent = this._hiddenContentSize * this._ratio;\n    const virtualStart = this._virtualStart;\n    const virtualEnd = this._virtualEnd;\n    const physicalCount = this._physicalCount;\n    let top = this._physicalTop + this._scrollOffset;\n    const bottom = this._physicalBottom + this._scrollOffset;\n    // This may be called outside of a scrollHandler, so use last cached position\n    const scrollTop = this._scrollPosition;\n    const scrollBottom = this._scrollBottom;\n\n    if (fromTop) {\n      ith = this._physicalStart;\n      offsetContent = scrollTop - top;\n    } else {\n      ith = this._physicalEnd;\n      offsetContent = bottom - scrollBottom;\n    }\n    // eslint-disable-next-line no-constant-condition\n    while (true) {\n      physicalItemHeight = this._getPhysicalSizeIncrement(ith);\n      offsetContent -= physicalItemHeight;\n      if (idxs.length >= physicalCount || offsetContent <= protectedOffsetContent) {\n        break;\n      }\n      if (fromTop) {\n        // Check that index is within the valid range.\n        if (virtualEnd + idxs.length + 1 >= this._virtualCount) {\n          break;\n        }\n        // Check that the index is not visible.\n        if (top + physicalItemHeight >= scrollTop - this._scrollOffset) {\n          break;\n        }\n        idxs.push(ith);\n        top += physicalItemHeight;\n        ith = (ith + 1) % physicalCount;\n      } else {\n        // Check that index is within the valid range.\n        if (virtualStart - idxs.length <= 0) {\n          break;\n        }\n        // Check that the index is not visible.\n        if (top + this._physicalSize - physicalItemHeight <= scrollBottom) {\n          break;\n        }\n        idxs.push(ith);\n        top -= physicalItemHeight;\n        ith = ith === 0 ? physicalCount - 1 : ith - 1;\n      }\n    }\n    return { indexes: idxs, physicalTop: top - this._scrollOffset };\n  },\n\n  /**\n   * Update the list of items, starting from the `_virtualStart` item.\n   * @param {!Array<number>=} itemSet\n   * @param {!Array<number>=} movingUp\n   */\n  _update(itemSet, movingUp) {\n    if ((itemSet && itemSet.length === 0) || this._physicalCount === 0) {\n      return;\n    }\n    this._assignModels(itemSet);\n    this._updateMetrics(itemSet);\n    // Adjust offset after measuring.\n    if (movingUp) {\n      while (movingUp.length) {\n        const idx = movingUp.pop();\n        this._physicalTop -= this._getPhysicalSizeIncrement(idx);\n      }\n    }\n    this._positionItems();\n    this._updateScrollerSize();\n  },\n\n  _isClientFull() {\n    return (\n      this._scrollBottom !== 0 &&\n      this._physicalBottom - 1 >= this._scrollBottom &&\n      this._physicalTop <= this._scrollPosition\n    );\n  },\n\n  /**\n   * Increases the pool size.\n   */\n  _increasePoolIfNeeded(count) {\n    const nextPhysicalCount = this._clamp(\n      this._physicalCount + count,\n      DEFAULT_PHYSICAL_COUNT,\n      this._virtualCount - this._virtualStart,\n    );\n    const delta = nextPhysicalCount - this._physicalCount;\n    let nextIncrease = Math.round(this._physicalCount * 0.5);\n\n    if (delta < 0) {\n      return;\n    }\n    if (delta > 0) {\n      const ts = window.performance.now();\n      // Concat arrays in place.\n      [].push.apply(this._physicalItems, this._createPool(delta));\n      // Push 0s into physicalSizes. Can't use Array.fill because IE11 doesn't\n      // support it.\n      for (let i = 0; i < delta; i++) {\n        this._physicalSizes.push(0);\n      }\n      this._physicalCount += delta;\n      // Update the physical start if it needs to preserve the model of the\n      // focused item. In this situation, the focused item is currently rendered\n      // and its model would have changed after increasing the pool if the\n      // physical start remained unchanged.\n      if (\n        this._physicalStart > this._physicalEnd &&\n        this._isIndexRendered(this._focusedVirtualIndex) &&\n        this._getPhysicalIndex(this._focusedVirtualIndex) < this._physicalEnd\n      ) {\n        this._physicalStart += delta;\n      }\n      this._update();\n      this._templateCost = (window.performance.now() - ts) / delta;\n      nextIncrease = Math.round(this._physicalCount * 0.5);\n    }\n    if (this._virtualEnd >= this._virtualCount - 1 || nextIncrease === 0) {\n      // Do nothing.\n    } else if (!this._isClientFull()) {\n      this._debounce('_increasePoolIfNeeded', this._increasePoolIfNeeded.bind(this, nextIncrease), microTask);\n    } else if (this._physicalSize < this._optPhysicalSize) {\n      // Yield and increase the pool during idle time until the physical size is\n      // optimal.\n      this._debounce(\n        '_increasePoolIfNeeded',\n        this._increasePoolIfNeeded.bind(this, this._clamp(Math.round(50 / this._templateCost), 1, nextIncrease)),\n        idlePeriod,\n      );\n    }\n  },\n\n  /**\n   * Renders the a new list.\n   */\n  _render() {\n    if (!this.isAttached || !this._isVisible) {\n      return;\n    }\n    if (this._physicalCount !== 0) {\n      const reusables = this._getReusables(true);\n      this._physicalTop = reusables.physicalTop;\n      this._virtualStart += reusables.indexes.length;\n      this._physicalStart += reusables.indexes.length;\n      this._update(reusables.indexes);\n      this._update();\n      this._increasePoolIfNeeded(0);\n    } else if (this._virtualCount > 0) {\n      // Initial render\n      this.updateViewportBoundaries();\n      this._increasePoolIfNeeded(DEFAULT_PHYSICAL_COUNT);\n    }\n  },\n\n  /**\n   * Called when the items have changed. That is, reassignments\n   * to `items`, splices or updates to a single item.\n   */\n  _itemsChanged(change) {\n    if (change.path === 'items') {\n      this._virtualStart = 0;\n      this._physicalTop = 0;\n      this._virtualCount = this.items ? this.items.length : 0;\n      this._physicalIndexForKey = {};\n      this._firstVisibleIndexVal = null;\n      this._lastVisibleIndexVal = null;\n      if (!this._physicalItems) {\n        this._physicalItems = [];\n      }\n      if (!this._physicalSizes) {\n        this._physicalSizes = [];\n      }\n      this._physicalStart = 0;\n      if (this._scrollTop > this._scrollOffset) {\n        this._resetScrollPosition(0);\n      }\n      this._debounce('_render', this._render, animationFrame);\n    }\n  },\n\n  /**\n   * Executes a provided function per every physical index in `itemSet`\n   * `itemSet` default value is equivalent to the entire set of physical\n   * indexes.\n   *\n   * @param {!function(number, number)} fn\n   * @param {!Array<number>=} itemSet\n   */\n  _iterateItems(fn, itemSet) {\n    let pidx, vidx, rtn, i;\n\n    if (arguments.length === 2 && itemSet) {\n      for (i = 0; i < itemSet.length; i++) {\n        pidx = itemSet[i];\n        vidx = this._computeVidx(pidx);\n        if ((rtn = fn.call(this, pidx, vidx)) != null) {\n          return rtn;\n        }\n      }\n    } else {\n      pidx = this._physicalStart;\n      vidx = this._virtualStart;\n      for (; pidx < this._physicalCount; pidx++, vidx++) {\n        if ((rtn = fn.call(this, pidx, vidx)) != null) {\n          return rtn;\n        }\n      }\n      for (pidx = 0; pidx < this._physicalStart; pidx++, vidx++) {\n        if ((rtn = fn.call(this, pidx, vidx)) != null) {\n          return rtn;\n        }\n      }\n    }\n  },\n\n  /**\n   * Returns the virtual index for a given physical index\n   *\n   * @param {number} pidx Physical index\n   * @return {number}\n   */\n  _computeVidx(pidx) {\n    if (pidx >= this._physicalStart) {\n      return this._virtualStart + (pidx - this._physicalStart);\n    }\n    return this._virtualStart + (this._physicalCount - this._physicalStart) + pidx;\n  },\n\n  /**\n   * Updates the position of the physical items.\n   */\n  _positionItems() {\n    this._adjustScrollPosition();\n\n    let y = this._physicalTop;\n\n    this._iterateItems((pidx) => {\n      this.translate3d(0, `${y}px`, 0, this._physicalItems[pidx]);\n      y += this._physicalSizes[pidx];\n    });\n  },\n\n  _getPhysicalSizeIncrement(pidx) {\n    return this._physicalSizes[pidx];\n  },\n\n  /**\n   * Adjusts the scroll position when it was overestimated.\n   */\n  _adjustScrollPosition() {\n    const deltaHeight =\n      this._virtualStart === 0 ? this._physicalTop : Math.min(this._scrollPosition + this._physicalTop, 0);\n    // Note: the delta can be positive or negative.\n    if (deltaHeight !== 0) {\n      this._physicalTop -= deltaHeight;\n      // This may be called outside of a scrollHandler, so use last cached position\n      const scrollTop = this._scrollPosition;\n      // Juking scroll position during interial scrolling on iOS is no bueno\n      if (!IOS_TOUCH_SCROLLING && scrollTop > 0) {\n        this._resetScrollPosition(scrollTop - deltaHeight);\n      }\n    }\n  },\n\n  /**\n   * Sets the position of the scroll.\n   */\n  _resetScrollPosition(pos) {\n    if (this.scrollTarget && pos >= 0) {\n      this._scrollTop = pos;\n      this._scrollPosition = this._scrollTop;\n    }\n  },\n\n  /**\n   * Sets the scroll height, that's the height of the content,\n   *\n   * @param {boolean=} forceUpdate If true, updates the height no matter what.\n   */\n  _updateScrollerSize(forceUpdate) {\n    const estScrollHeight =\n      this._physicalBottom +\n      Math.max(this._virtualCount - this._physicalCount - this._virtualStart, 0) * this._physicalAverage;\n\n    this._estScrollHeight = estScrollHeight;\n\n    // Amortize height adjustment, so it won't trigger large repaints too often.\n    if (\n      forceUpdate ||\n      this._scrollHeight === 0 ||\n      this._scrollPosition >= estScrollHeight - this._physicalSize ||\n      Math.abs(estScrollHeight - this._scrollHeight) >= this._viewportHeight\n    ) {\n      this.$.items.style.height = `${estScrollHeight}px`;\n      this._scrollHeight = estScrollHeight;\n    }\n  },\n\n  /**\n   * Scroll to a specific index in the virtual list regardless\n   * of the physical items in the DOM tree.\n   *\n   * @method scrollToIndex\n   * @param {number} idx The index of the item\n   */\n  scrollToIndex(idx) {\n    if (typeof idx !== 'number' || idx < 0 || idx > this.items.length - 1) {\n      return;\n    }\n    flush();\n    // Items should have been rendered prior scrolling to an index.\n    if (this._physicalCount === 0) {\n      return;\n    }\n    idx = this._clamp(idx, 0, this._virtualCount - 1);\n    // Update the virtual start only when needed.\n    if (!this._isIndexRendered(idx) || idx >= this._maxVirtualStart) {\n      this._virtualStart = idx - 1;\n    }\n    this._assignModels();\n    this._updateMetrics();\n    // Estimate new physical offset.\n    this._physicalTop = this._virtualStart * this._physicalAverage;\n\n    let currentTopItem = this._physicalStart;\n    let currentVirtualItem = this._virtualStart;\n    let targetOffsetTop = 0;\n    const hiddenContentSize = this._hiddenContentSize;\n    // Scroll to the item as much as we can.\n    while (currentVirtualItem < idx && targetOffsetTop <= hiddenContentSize) {\n      targetOffsetTop += this._getPhysicalSizeIncrement(currentTopItem);\n      currentTopItem = (currentTopItem + 1) % this._physicalCount;\n      currentVirtualItem += 1;\n    }\n    this._updateScrollerSize(true);\n    this._positionItems();\n    this._resetScrollPosition(this._physicalTop + this._scrollOffset + targetOffsetTop);\n    this._increasePoolIfNeeded(0);\n    // Clear cached visible index.\n    this._firstVisibleIndexVal = null;\n    this._lastVisibleIndexVal = null;\n  },\n\n  /**\n   * Reset the physical average and the average count.\n   */\n  _resetAverage() {\n    this._physicalAverage = 0;\n    this._physicalAverageCount = 0;\n  },\n\n  /**\n   * A handler for the `iron-resize` event triggered by `IronResizableBehavior`\n   * when the element is resized.\n   */\n  _resizeHandler() {\n    this._debounce(\n      '_render',\n      () => {\n        // Clear cached visible index.\n        this._firstVisibleIndexVal = null;\n        this._lastVisibleIndexVal = null;\n        if (this._isVisible) {\n          this.updateViewportBoundaries();\n          // Reinstall the scroll event listener.\n          this.toggleScrollListener(true);\n          this._resetAverage();\n          this._render();\n        } else {\n          // Uninstall the scroll event listener.\n          this.toggleScrollListener(false);\n        }\n      },\n      animationFrame,\n    );\n  },\n\n  _isIndexRendered(idx) {\n    return idx >= this._virtualStart && idx <= this._virtualEnd;\n  },\n\n  _getPhysicalIndex(vidx) {\n    return (this._physicalStart + (vidx - this._virtualStart)) % this._physicalCount;\n  },\n\n  _clamp(v, min, max) {\n    return Math.min(max, Math.max(min, v));\n  },\n\n  _debounce(name, cb, asyncModule) {\n    if (!this._debouncers) {\n      this._debouncers = {};\n    }\n    this._debouncers[name] = Debouncer.debounce(this._debouncers[name], asyncModule, cb.bind(this));\n    enqueueDebouncer(this._debouncers[name]);\n  },\n};\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n/* eslint-disable @typescript-eslint/member-ordering */\n// https://github.com/vaadin/eslint-config-vaadin/issues/33\nimport { animationFrame, timeOut } from './async.js';\nimport { isSafari } from './browser-utils.js';\nimport { Debouncer, flush } from './debounce.js';\nimport { ironList } from './iron-list-core.js';\n\n// Iron-list can by default handle sizes up to around 100000.\n// When the size is larger than MAX_VIRTUAL_COUNT _vidxOffset is used\nconst MAX_VIRTUAL_COUNT = 100000;\nconst OFFSET_ADJUST_MIN_THRESHOLD = 1000;\n\nexport class IronListAdapter {\n  constructor({ createElements, updateElement, scrollTarget, scrollContainer, elementsContainer, reorderElements }) {\n    this.isAttached = true;\n    this._vidxOffset = 0;\n    this.createElements = createElements;\n    this.updateElement = updateElement;\n    this.scrollTarget = scrollTarget;\n    this.scrollContainer = scrollContainer;\n    this.elementsContainer = elementsContainer || scrollContainer;\n    this.reorderElements = reorderElements;\n    // Iron-list uses this value to determine how many pages of elements to render\n    this._maxPages = 1.3;\n\n    // Placeholder height (used for sizing elements that have intrinsic 0 height after update)\n    this.__placeholderHeight = 200;\n    // A queue of 10 previous element heights\n    this.__elementHeightQueue = Array(10);\n\n    this.timeouts = {\n      SCROLL_REORDER: 500,\n      IGNORE_WHEEL: 500,\n      FIX_INVALID_ITEM_POSITIONING: 100,\n    };\n\n    this.__resizeObserver = new ResizeObserver(() => this._resizeHandler());\n\n    if (getComputedStyle(this.scrollTarget).overflow === 'visible') {\n      this.scrollTarget.style.overflow = 'auto';\n    }\n\n    if (getComputedStyle(this.scrollContainer).position === 'static') {\n      this.scrollContainer.style.position = 'relative';\n    }\n\n    this.__resizeObserver.observe(this.scrollTarget);\n    this.scrollTarget.addEventListener('scroll', () => this._scrollHandler());\n\n    this._scrollLineHeight = this._getScrollLineHeight();\n    this.scrollTarget.addEventListener('wheel', (e) => this.__onWheel(e));\n\n    if (this.reorderElements) {\n      // Reordering the physical elements cancels the user's grab of the scroll bar handle on Safari.\n      // Need to defer reordering until the user lets go of the scroll bar handle.\n      this.scrollTarget.addEventListener('mousedown', () => {\n        this.__mouseDown = true;\n      });\n      this.scrollTarget.addEventListener('mouseup', () => {\n        this.__mouseDown = false;\n        if (this.__pendingReorder) {\n          this.__reorderElements();\n        }\n      });\n    }\n  }\n\n  get scrollOffset() {\n    return 0;\n  }\n\n  get adjustedFirstVisibleIndex() {\n    return this.firstVisibleIndex + this._vidxOffset;\n  }\n\n  get adjustedLastVisibleIndex() {\n    return this.lastVisibleIndex + this._vidxOffset;\n  }\n\n  scrollToIndex(index) {\n    if (typeof index !== 'number' || isNaN(index) || this.size === 0 || !this.scrollTarget.offsetHeight) {\n      return;\n    }\n    index = this._clamp(index, 0, this.size - 1);\n\n    const visibleElementCount = this.__getVisibleElements().length;\n    let targetVirtualIndex = Math.floor((index / this.size) * this._virtualCount);\n    if (this._virtualCount - targetVirtualIndex < visibleElementCount) {\n      targetVirtualIndex = this._virtualCount - (this.size - index);\n      this._vidxOffset = this.size - this._virtualCount;\n    } else if (targetVirtualIndex < visibleElementCount) {\n      if (index < OFFSET_ADJUST_MIN_THRESHOLD) {\n        targetVirtualIndex = index;\n        this._vidxOffset = 0;\n      } else {\n        targetVirtualIndex = OFFSET_ADJUST_MIN_THRESHOLD;\n        this._vidxOffset = index - targetVirtualIndex;\n      }\n    } else {\n      this._vidxOffset = index - targetVirtualIndex;\n    }\n\n    this.__skipNextVirtualIndexAdjust = true;\n    super.scrollToIndex(targetVirtualIndex);\n\n    if (this.adjustedFirstVisibleIndex !== index && this._scrollTop < this._maxScrollTop && !this.grid) {\n      // Workaround an iron-list issue by manually adjusting the scroll position\n      this._scrollTop -= this.__getIndexScrollOffset(index) || 0;\n    }\n    this._scrollHandler();\n  }\n\n  flush() {\n    // The scroll target is hidden.\n    if (this.scrollTarget.offsetHeight === 0) {\n      return;\n    }\n\n    this._resizeHandler();\n    flush();\n    this._scrollHandler();\n    if (this.__fixInvalidItemPositioningDebouncer) {\n      this.__fixInvalidItemPositioningDebouncer.flush();\n    }\n    if (this.__scrollReorderDebouncer) {\n      this.__scrollReorderDebouncer.flush();\n    }\n    if (this.__debouncerWheelAnimationFrame) {\n      this.__debouncerWheelAnimationFrame.flush();\n    }\n  }\n\n  update(startIndex = 0, endIndex = this.size - 1) {\n    const updatedElements = [];\n    this.__getVisibleElements().forEach((el) => {\n      if (el.__virtualIndex >= startIndex && el.__virtualIndex <= endIndex) {\n        this.__updateElement(el, el.__virtualIndex, true);\n        updatedElements.push(el);\n      }\n    });\n\n    this.__afterElementsUpdated(updatedElements);\n  }\n\n  /**\n   * Updates the height for a given set of items.\n   *\n   * @param {!Array<number>=} itemSet\n   */\n  _updateMetrics(itemSet) {\n    // Make sure we distributed all the physical items\n    // so we can measure them.\n    flush();\n\n    let newPhysicalSize = 0;\n    let oldPhysicalSize = 0;\n    const prevAvgCount = this._physicalAverageCount;\n    const prevPhysicalAvg = this._physicalAverage;\n\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    this._iterateItems((pidx, vidx) => {\n      oldPhysicalSize += this._physicalSizes[pidx];\n      this._physicalSizes[pidx] = Math.ceil(this.__getBorderBoxHeight(this._physicalItems[pidx]));\n      newPhysicalSize += this._physicalSizes[pidx];\n      this._physicalAverageCount += this._physicalSizes[pidx] ? 1 : 0;\n    }, itemSet);\n\n    this._physicalSize = this._physicalSize + newPhysicalSize - oldPhysicalSize;\n\n    // Update the average if it measured something.\n    if (this._physicalAverageCount !== prevAvgCount) {\n      this._physicalAverage = Math.round(\n        (prevPhysicalAvg * prevAvgCount + newPhysicalSize) / this._physicalAverageCount,\n      );\n    }\n  }\n\n  __getBorderBoxHeight(el) {\n    const style = getComputedStyle(el);\n\n    const itemHeight = parseFloat(style.height) || 0;\n\n    if (style.boxSizing === 'border-box') {\n      return itemHeight;\n    }\n\n    const paddingBottom = parseFloat(style.paddingBottom) || 0;\n    const paddingTop = parseFloat(style.paddingTop) || 0;\n    const borderBottomWidth = parseFloat(style.borderBottomWidth) || 0;\n    const borderTopWidth = parseFloat(style.borderTopWidth) || 0;\n\n    return itemHeight + paddingBottom + paddingTop + borderBottomWidth + borderTopWidth;\n  }\n\n  __updateElement(el, index, forceSameIndexUpdates) {\n    // Clean up temporary placeholder sizing\n    if (el.style.paddingTop) {\n      el.style.paddingTop = '';\n    }\n\n    if (!this.__preventElementUpdates && (el.__lastUpdatedIndex !== index || forceSameIndexUpdates)) {\n      this.updateElement(el, index);\n      el.__lastUpdatedIndex = index;\n    }\n  }\n\n  /**\n   * Called synchronously right after elements have been updated.\n   * This is a good place to do any post-update work.\n   *\n   * @param {!Array<!HTMLElement>} updatedElements\n   */\n  __afterElementsUpdated(updatedElements) {\n    updatedElements.forEach((el) => {\n      const elementHeight = el.offsetHeight;\n      if (elementHeight === 0) {\n        // If the elements have 0 height after update (for example due to lazy rendering),\n        // it results in iron-list requesting to create an unlimited count of elements.\n        // Assign a temporary placeholder sizing to elements that would otherwise end up having\n        // no height.\n        el.style.paddingTop = `${this.__placeholderHeight}px`;\n\n        // Manually schedule the resize handler to make sure the placeholder padding is\n        // cleared in case the resize observer never triggers.\n        this.__placeholderClearDebouncer = Debouncer.debounce(this.__placeholderClearDebouncer, animationFrame, () =>\n          this._resizeHandler(),\n        );\n      } else {\n        // Add element height to the queue\n        this.__elementHeightQueue.push(elementHeight);\n        this.__elementHeightQueue.shift();\n\n        // Calculate new placeholder height based on the average of the defined values in the\n        // element height queue\n        const filteredHeights = this.__elementHeightQueue.filter((h) => h !== undefined);\n        this.__placeholderHeight = Math.round(filteredHeights.reduce((a, b) => a + b, 0) / filteredHeights.length);\n      }\n    });\n  }\n\n  __getIndexScrollOffset(index) {\n    const element = this.__getVisibleElements().find((el) => el.__virtualIndex === index);\n    return element ? this.scrollTarget.getBoundingClientRect().top - element.getBoundingClientRect().top : undefined;\n  }\n\n  get size() {\n    return this.__size;\n  }\n\n  set size(size) {\n    if (size === this.size) {\n      return;\n    }\n    // Cancel active debouncers\n    if (this.__fixInvalidItemPositioningDebouncer) {\n      this.__fixInvalidItemPositioningDebouncer.cancel();\n    }\n    if (this._debouncers && this._debouncers._increasePoolIfNeeded) {\n      // Avoid creating unnecessary elements on the following flush()\n      this._debouncers._increasePoolIfNeeded.cancel();\n    }\n\n    // Change the size\n    this.__size = size;\n\n    if (!this._physicalItems) {\n      // Not initialized yet\n      this._itemsChanged({\n        path: 'items',\n      });\n      this.__preventElementUpdates = true;\n      flush();\n      this.__preventElementUpdates = false;\n    } else {\n      // Already initialized, just update _virtualCount\n      this._virtualCount = this.items.length;\n    }\n\n    // When reducing size while invisible, iron-list does not update items, so\n    // their hidden state is not updated and their __lastUpdatedIndex is not\n    // reset. In that case force an update here.\n    if (!this._isVisible) {\n      this._assignModels();\n    }\n\n    if (!this.elementsContainer.children.length) {\n      requestAnimationFrame(() => this._resizeHandler());\n    }\n\n    // Schedule and flush a resize handler. This will cause a\n    // re-render for the elements.\n    this._resizeHandler();\n    flush();\n  }\n\n  /** @private */\n  get _scrollTop() {\n    return this.scrollTarget.scrollTop;\n  }\n\n  /** @private */\n  set _scrollTop(top) {\n    this.scrollTarget.scrollTop = top;\n  }\n\n  /** @private */\n  get items() {\n    return {\n      length: Math.min(this.size, MAX_VIRTUAL_COUNT),\n    };\n  }\n\n  /** @private */\n  get offsetHeight() {\n    return this.scrollTarget.offsetHeight;\n  }\n\n  /** @private */\n  get $() {\n    return {\n      items: this.scrollContainer,\n    };\n  }\n\n  /** @private */\n  updateViewportBoundaries() {\n    const styles = window.getComputedStyle(this.scrollTarget);\n    this._scrollerPaddingTop = this.scrollTarget === this ? 0 : parseInt(styles['padding-top'], 10);\n    this._isRTL = Boolean(styles.direction === 'rtl');\n    this._viewportWidth = this.elementsContainer.offsetWidth;\n    this._viewportHeight = this.scrollTarget.offsetHeight;\n    this._scrollPageHeight = this._viewportHeight - this._scrollLineHeight;\n    if (this.grid) {\n      this._updateGridMetrics();\n    }\n  }\n\n  /** @private */\n  setAttribute() {}\n\n  /** @private */\n  _createPool(size) {\n    const physicalItems = this.createElements(size);\n    const fragment = document.createDocumentFragment();\n    physicalItems.forEach((el) => {\n      el.style.position = 'absolute';\n      fragment.appendChild(el);\n      this.__resizeObserver.observe(el);\n    });\n    this.elementsContainer.appendChild(fragment);\n    return physicalItems;\n  }\n\n  /** @private */\n  _assignModels(itemSet) {\n    const updatedElements = [];\n    this._iterateItems((pidx, vidx) => {\n      const el = this._physicalItems[pidx];\n      el.hidden = vidx >= this.size;\n      if (!el.hidden) {\n        el.__virtualIndex = vidx + (this._vidxOffset || 0);\n        this.__updateElement(el, el.__virtualIndex);\n        updatedElements.push(el);\n      } else {\n        delete el.__lastUpdatedIndex;\n      }\n    }, itemSet);\n\n    this.__afterElementsUpdated(updatedElements);\n  }\n\n  /** @private */\n  _isClientFull() {\n    // Workaround an issue in iron-list that can cause it to freeze on fast scroll\n    setTimeout(() => {\n      this.__clientFull = true;\n    });\n    return this.__clientFull || super._isClientFull();\n  }\n\n  /** @private */\n  translate3d(_x, y, _z, el) {\n    el.style.transform = `translateY(${y})`;\n  }\n\n  /** @private */\n  toggleScrollListener() {}\n\n  _scrollHandler() {\n    // The scroll target is hidden.\n    if (this.scrollTarget.offsetHeight === 0) {\n      return;\n    }\n\n    this._adjustVirtualIndexOffset(this._scrollTop - (this.__previousScrollTop || 0));\n    const delta = this.scrollTarget.scrollTop - this._scrollPosition;\n\n    super._scrollHandler();\n\n    if (this._physicalCount !== 0) {\n      const isScrollingDown = delta >= 0;\n      const reusables = this._getReusables(!isScrollingDown);\n\n      if (reusables.indexes.length) {\n        // After running super._scrollHandler, fix internal properties to workaround an iron-list issue.\n        // See https://github.com/vaadin/web-components/issues/1691\n        this._physicalTop = reusables.physicalTop;\n\n        if (isScrollingDown) {\n          this._virtualStart -= reusables.indexes.length;\n          this._physicalStart -= reusables.indexes.length;\n        } else {\n          this._virtualStart += reusables.indexes.length;\n          this._physicalStart += reusables.indexes.length;\n        }\n        this._resizeHandler();\n      }\n    }\n\n    if (delta) {\n      // There was a change in scroll top. Schedule a check for invalid item positioning.\n      this.__fixInvalidItemPositioningDebouncer = Debouncer.debounce(\n        this.__fixInvalidItemPositioningDebouncer,\n        timeOut.after(this.timeouts.FIX_INVALID_ITEM_POSITIONING),\n        () => this.__fixInvalidItemPositioning(),\n      );\n    }\n\n    if (this.reorderElements) {\n      this.__scrollReorderDebouncer = Debouncer.debounce(\n        this.__scrollReorderDebouncer,\n        timeOut.after(this.timeouts.SCROLL_REORDER),\n        () => this.__reorderElements(),\n      );\n    }\n\n    this.__previousScrollTop = this._scrollTop;\n\n    // If the first visible index is not 0 when scrolled to the top,\n    // scroll to index 0 to fix the issue.\n    if (this._scrollTop === 0 && this.firstVisibleIndex !== 0 && Math.abs(delta) > 0) {\n      this.scrollToIndex(0);\n    }\n  }\n\n  /**\n   * Work around an iron-list issue with invalid item positioning.\n   * See https://github.com/vaadin/flow-components/issues/4306\n   * @private\n   */\n  __fixInvalidItemPositioning() {\n    if (!this.scrollTarget.isConnected) {\n      return;\n    }\n\n    // Check if the first physical item element is below the top of the viewport\n    const physicalTopBelowTop = this._physicalTop > this._scrollTop;\n    // Check if the last physical item element is above the bottom of the viewport\n    const physicalBottomAboveBottom = this._physicalBottom < this._scrollBottom;\n\n    // Check if the first index is visible\n    const firstIndexVisible = this.adjustedFirstVisibleIndex === 0;\n    // Check if the last index is visible\n    const lastIndexVisible = this.adjustedLastVisibleIndex === this.size - 1;\n\n    if ((physicalTopBelowTop && !firstIndexVisible) || (physicalBottomAboveBottom && !lastIndexVisible)) {\n      // Invalid state! Try to recover.\n\n      const isScrollingDown = physicalBottomAboveBottom;\n      // Set the \"_ratio\" property temporarily to 0 to make iron-list's _getReusables\n      // place all the free physical items on one side of the viewport.\n      const originalRatio = this._ratio;\n      this._ratio = 0;\n      // Fake a scroll change to make _scrollHandler place the physical items\n      // on the desired side.\n      this._scrollPosition = this._scrollTop + (isScrollingDown ? -1 : 1);\n      this._scrollHandler();\n      // Restore the original \"_ratio\" value.\n      this._ratio = originalRatio;\n    }\n  }\n\n  /** @private */\n  __onWheel(e) {\n    if (e.ctrlKey || this._hasScrolledAncestor(e.target, e.deltaX, e.deltaY)) {\n      return;\n    }\n\n    let deltaY = e.deltaY;\n    if (e.deltaMode === WheelEvent.DOM_DELTA_LINE) {\n      // Scrolling by \"lines of text\" instead of pixels\n      deltaY *= this._scrollLineHeight;\n    } else if (e.deltaMode === WheelEvent.DOM_DELTA_PAGE) {\n      // Scrolling by \"pages\" instead of pixels\n      deltaY *= this._scrollPageHeight;\n    }\n\n    if (!this._deltaYAcc) {\n      this._deltaYAcc = 0;\n    }\n\n    if (this._wheelAnimationFrame) {\n      // Accumulate wheel delta while a frame is being processed\n      this._deltaYAcc += deltaY;\n      e.preventDefault();\n      return;\n    }\n\n    deltaY += this._deltaYAcc;\n    this._deltaYAcc = 0;\n\n    this._wheelAnimationFrame = true;\n    this.__debouncerWheelAnimationFrame = Debouncer.debounce(\n      this.__debouncerWheelAnimationFrame,\n      animationFrame,\n      () => {\n        this._wheelAnimationFrame = false;\n      },\n    );\n\n    const momentum = Math.abs(e.deltaX) + Math.abs(deltaY);\n\n    if (this._canScroll(this.scrollTarget, e.deltaX, deltaY)) {\n      e.preventDefault();\n      this.scrollTarget.scrollTop += deltaY;\n      this.scrollTarget.scrollLeft += e.deltaX;\n\n      this._hasResidualMomentum = true;\n\n      this._ignoreNewWheel = true;\n      this._debouncerIgnoreNewWheel = Debouncer.debounce(\n        this._debouncerIgnoreNewWheel,\n        timeOut.after(this.timeouts.IGNORE_WHEEL),\n        () => {\n          this._ignoreNewWheel = false;\n        },\n      );\n    } else if ((this._hasResidualMomentum && momentum <= this._previousMomentum) || this._ignoreNewWheel) {\n      e.preventDefault();\n    } else if (momentum > this._previousMomentum) {\n      this._hasResidualMomentum = false;\n    }\n    this._previousMomentum = momentum;\n  }\n\n  /**\n   * Determines if the element has an ancestor that handles the scroll delta prior to this\n   *\n   * @private\n   */\n  _hasScrolledAncestor(el, deltaX, deltaY) {\n    if (el === this.scrollTarget || el === this.scrollTarget.getRootNode().host) {\n      return false;\n    } else if (\n      this._canScroll(el, deltaX, deltaY) &&\n      ['auto', 'scroll'].indexOf(getComputedStyle(el).overflow) !== -1\n    ) {\n      return true;\n    } else if (el !== this && el.parentElement) {\n      return this._hasScrolledAncestor(el.parentElement, deltaX, deltaY);\n    }\n  }\n\n  _canScroll(el, deltaX, deltaY) {\n    return (\n      (deltaY > 0 && el.scrollTop < el.scrollHeight - el.offsetHeight) ||\n      (deltaY < 0 && el.scrollTop > 0) ||\n      (deltaX > 0 && el.scrollLeft < el.scrollWidth - el.offsetWidth) ||\n      (deltaX < 0 && el.scrollLeft > 0)\n    );\n  }\n\n  /**\n   * Increases the pool size.\n   * @override\n   */\n  _increasePoolIfNeeded(count) {\n    if (this._physicalCount > 2 && count) {\n      // The iron-list logic has already created some physical items and\n      // has decided to create more. Since each item creation round is\n      // expensive, let's try to create the remaining items in one go.\n\n      // Calculate the total item count that would be needed to fill the viewport\n      // plus the buffer assuming rest of the items to be of the average size\n      // of the items already created.\n      const totalItemCount = Math.ceil(this._optPhysicalSize / this._physicalAverage);\n      const missingItemCount = totalItemCount - this._physicalCount;\n      // Create the remaining items in one go. Use a maximum of 100 items\n      // as a safety measure.\n      super._increasePoolIfNeeded(Math.max(count, Math.min(100, missingItemCount)));\n    } else {\n      super._increasePoolIfNeeded(count);\n    }\n  }\n\n  /**\n   * @returns {Number|undefined} - The browser's default font-size in pixels\n   * @private\n   */\n  _getScrollLineHeight() {\n    const el = document.createElement('div');\n    el.style.fontSize = 'initial';\n    el.style.display = 'none';\n    document.body.appendChild(el);\n    const fontSize = window.getComputedStyle(el).fontSize;\n    document.body.removeChild(el);\n    return fontSize ? window.parseInt(fontSize) : undefined;\n  }\n\n  __getVisibleElements() {\n    return Array.from(this.elementsContainer.children).filter((element) => !element.hidden);\n  }\n\n  /** @private */\n  __reorderElements() {\n    if (this.__mouseDown) {\n      this.__pendingReorder = true;\n      return;\n    }\n    this.__pendingReorder = false;\n\n    const adjustedVirtualStart = this._virtualStart + (this._vidxOffset || 0);\n\n    // Which row to use as a target?\n    const visibleElements = this.__getVisibleElements();\n\n    const elementWithFocus = visibleElements.find(\n      (element) =>\n        element.contains(this.elementsContainer.getRootNode().activeElement) ||\n        element.contains(this.scrollTarget.getRootNode().activeElement),\n    );\n    const targetElement = elementWithFocus || visibleElements[0];\n    if (!targetElement) {\n      // All elements are hidden, don't reorder\n      return;\n    }\n\n    // Where the target row should be?\n    const targetPhysicalIndex = targetElement.__virtualIndex - adjustedVirtualStart;\n\n    // Reodrer the DOM elements to keep the target row at the target physical index\n    const delta = visibleElements.indexOf(targetElement) - targetPhysicalIndex;\n    if (delta > 0) {\n      for (let i = 0; i < delta; i++) {\n        this.elementsContainer.appendChild(visibleElements[i]);\n      }\n    } else if (delta < 0) {\n      for (let i = visibleElements.length + delta; i < visibleElements.length; i++) {\n        this.elementsContainer.insertBefore(visibleElements[i], visibleElements[0]);\n      }\n    }\n\n    // Due to a rendering bug, reordering the rows can make parts of the scroll target disappear\n    // on Safari when using sticky positioning in case the scroll target is inside a flexbox.\n    // This issue manifests with grid (the header can disappear if grid is used inside a flexbox)\n    if (isSafari) {\n      const { transform } = this.scrollTarget.style;\n      this.scrollTarget.style.transform = 'translateZ(0)';\n      setTimeout(() => {\n        this.scrollTarget.style.transform = transform;\n      });\n    }\n  }\n\n  /** @private */\n  _adjustVirtualIndexOffset(delta) {\n    if (this._virtualCount >= this.size) {\n      this._vidxOffset = 0;\n    } else if (this.__skipNextVirtualIndexAdjust) {\n      this.__skipNextVirtualIndexAdjust = false;\n    } else if (Math.abs(delta) > 10000) {\n      // Process a large scroll position change\n      const scale = this._scrollTop / (this.scrollTarget.scrollHeight - this.scrollTarget.offsetHeight);\n      const offset = scale * this.size;\n      this._vidxOffset = Math.round(offset - scale * this._virtualCount);\n    } else {\n      // Make sure user can always swipe/wheel scroll to the start and end\n      const oldOffset = this._vidxOffset;\n      const threshold = OFFSET_ADJUST_MIN_THRESHOLD;\n      const maxShift = 100;\n\n      // Near start\n      if (this._scrollTop === 0) {\n        this._vidxOffset = 0;\n        if (oldOffset !== this._vidxOffset) {\n          super.scrollToIndex(0);\n        }\n      } else if (this.firstVisibleIndex < threshold && this._vidxOffset > 0) {\n        this._vidxOffset -= Math.min(this._vidxOffset, maxShift);\n        super.scrollToIndex(this.firstVisibleIndex + (oldOffset - this._vidxOffset));\n      }\n\n      // Near end\n      const maxOffset = this.size - this._virtualCount;\n      if (this._scrollTop >= this._maxScrollTop && this._maxScrollTop > 0) {\n        this._vidxOffset = maxOffset;\n        if (oldOffset !== this._vidxOffset) {\n          super.scrollToIndex(this._virtualCount - 1);\n        }\n      } else if (this.firstVisibleIndex > this._virtualCount - threshold && this._vidxOffset < maxOffset) {\n        this._vidxOffset += Math.min(maxOffset - this._vidxOffset, maxShift);\n        super.scrollToIndex(this.firstVisibleIndex - (this._vidxOffset - oldOffset));\n      }\n    }\n  }\n}\n\nObject.setPrototypeOf(IronListAdapter.prototype, ironList);\n","import { IronListAdapter } from './virtualizer-iron-list-adapter.js';\n\nexport class Virtualizer {\n  /**\n   * @typedef {Object} VirtualizerConfig\n   * @property {Function} createElements Function that returns the given number of new elements\n   * @property {Function} updateElement Function that updates the element at a specific index\n   * @property {HTMLElement} scrollTarget Reference to the scrolling element\n   * @property {HTMLElement} scrollContainer Reference to a wrapper for the item elements (or a slot) inside the scrollTarget\n   * @property {HTMLElement | undefined} elementsContainer Reference to the container in which the item elements are placed, defaults to scrollContainer\n   * @property {boolean | undefined} reorderElements Determines whether the physical item elements should be kept in order in the DOM\n   * @param {VirtualizerConfig} config Configuration for the virtualizer\n   */\n  constructor(config) {\n    this.__adapter = new IronListAdapter(config);\n  }\n\n  /**\n   * Gets the index of the first visible item in the viewport.\n   *\n   * @return {number}\n   */\n  get firstVisibleIndex() {\n    return this.__adapter.adjustedFirstVisibleIndex;\n  }\n\n  /**\n   * Gets the index of the last visible item in the viewport.\n   *\n   * @return {number}\n   */\n  get lastVisibleIndex() {\n    return this.__adapter.adjustedLastVisibleIndex;\n  }\n\n  /**\n   * The size of the virtualizer\n   * @return {number | undefined} The size of the virtualizer\n   */\n  get size() {\n    return this.__adapter.size;\n  }\n\n  /**\n   * The size of the virtualizer\n   * @param {number} size The size of the virtualizer\n   */\n  set size(size) {\n    this.__adapter.size = size;\n  }\n\n  /**\n   * Scroll to a specific index in the virtual list\n   *\n   * @method scrollToIndex\n   * @param {number} index The index of the item\n   */\n  scrollToIndex(index) {\n    this.__adapter.scrollToIndex(index);\n  }\n\n  /**\n   * Requests the virtualizer to re-render the item elements on an index range, if currently in the DOM\n   *\n   * @method update\n   * @param {number | undefined} startIndex The start index of the range\n   * @param {number | undefined} endIndex The end index of the range\n   */\n  update(startIndex = 0, endIndex = this.size - 1) {\n    this.__adapter.update(startIndex, endIndex);\n  }\n\n  /**\n   * Flushes active asynchronous tasks so that the component and the DOM end up in a stable state\n   *\n   * @method update\n   * @param {number | undefined} startIndex The start index of the range\n   * @param {number | undefined} endIndex The end index of the range\n   */\n  flush() {\n    this.__adapter.flush();\n  }\n}\n","/**\n * @license\n * Copyright (c) 2015 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\n\n/*\n * Placeholder object class representing items being loaded.\n *\n * @private\n */\nexport const ComboBoxPlaceholder = class ComboBoxPlaceholder {\n  toString() {\n    return '';\n  }\n};\n","/**\n * @license\n * Copyright (c) 2015 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { generateUniqueId } from '@vaadin/component-base/src/unique-id-utils.js';\nimport { Virtualizer } from '@vaadin/component-base/src/virtualizer.js';\nimport { ComboBoxPlaceholder } from './vaadin-combo-box-placeholder.js';\n\n/**\n * @polymerMixin\n */\nexport const ComboBoxScrollerMixin = (superClass) =>\n  class ComboBoxScrollerMixin extends superClass {\n    static get properties() {\n      return {\n        /**\n         * A full set of items to filter the visible options from.\n         * Set to an empty array when combo-box is not opened.\n         */\n        items: {\n          type: Array,\n          observer: '__itemsChanged',\n        },\n\n        /**\n         * Index of an item that has focus outline and is scrolled into view.\n         * The actual focus still remains in the input field.\n         */\n        focusedIndex: {\n          type: Number,\n          observer: '__focusedIndexChanged',\n        },\n\n        /**\n         * Set to true while combo-box fetches new page from the data provider.\n         */\n        loading: {\n          type: Boolean,\n          observer: '__loadingChanged',\n        },\n\n        /**\n         * Whether the combo-box is currently opened or not. If set to false,\n         * calling `scrollIntoView` does not have any effect.\n         */\n        opened: {\n          type: Boolean,\n          observer: '__openedChanged',\n        },\n\n        /**\n         * The selected item from the `items` array.\n         */\n        selectedItem: {\n          type: Object,\n          observer: '__selectedItemChanged',\n        },\n\n        /**\n         * Path for the id of the item, used to detect whether the item is selected.\n         */\n        itemIdPath: {\n          type: String,\n        },\n\n        /**\n         * Reference to the owner (combo-box owner), used by the item elements.\n         */\n        owner: {\n          type: Object,\n        },\n\n        /**\n         * Function used to set a label for every combo-box item.\n         */\n        getItemLabel: {\n          type: Object,\n        },\n\n        /**\n         * Function used to render the content of every combo-box item.\n         */\n        renderer: {\n          type: Object,\n          observer: '__rendererChanged',\n        },\n\n        /**\n         * Used to propagate the `theme` attribute from the host element.\n         */\n        theme: {\n          type: String,\n        },\n      };\n    }\n\n    constructor() {\n      super();\n      this.__boundOnItemClick = this.__onItemClick.bind(this);\n    }\n\n    /** @private */\n    get _viewportTotalPaddingBottom() {\n      if (this._cachedViewportTotalPaddingBottom === undefined) {\n        const itemsStyle = window.getComputedStyle(this.$.selector);\n        this._cachedViewportTotalPaddingBottom = [itemsStyle.paddingBottom, itemsStyle.borderBottomWidth]\n          .map((v) => {\n            return parseInt(v, 10);\n          })\n          .reduce((sum, v) => {\n            return sum + v;\n          });\n      }\n\n      return this._cachedViewportTotalPaddingBottom;\n    }\n\n    /** @protected */\n    ready() {\n      super.ready();\n\n      this.setAttribute('role', 'listbox');\n\n      // Ensure every instance has unique ID\n      this.id = `${this.localName}-${generateUniqueId()}`;\n\n      // Allow extensions to customize tag name for the items\n      this.__hostTagName = this.constructor.is.replace('-scroller', '');\n\n      this.addEventListener('click', (e) => e.stopPropagation());\n\n      this.__patchWheelOverScrolling();\n\n      this.__virtualizer = new Virtualizer({\n        createElements: this.__createElements.bind(this),\n        updateElement: this._updateElement.bind(this),\n        elementsContainer: this,\n        scrollTarget: this,\n        scrollContainer: this.$.selector,\n      });\n    }\n\n    /**\n     * Requests an update for the virtualizer to re-render items.\n     */\n    requestContentUpdate() {\n      if (this.__virtualizer) {\n        this.__virtualizer.update();\n      }\n    }\n\n    /**\n     * Scrolls an item at given index into view and adjusts `scrollTop`\n     * so that the element gets fully visible on Arrow Down key press.\n     * @param {number} index\n     */\n    scrollIntoView(index) {\n      if (!(this.opened && index >= 0)) {\n        return;\n      }\n\n      const visibleItemsCount = this._visibleItemsCount();\n\n      let targetIndex = index;\n\n      if (index > this.__virtualizer.lastVisibleIndex - 1) {\n        // Index is below the bottom, scrolling down. Make the item appear at the bottom.\n        // First scroll to target (will be at the top of the scroller) to make sure it's rendered.\n        this.__virtualizer.scrollToIndex(index);\n        // Then calculate the index for the following scroll (to get the target to bottom of the scroller).\n        targetIndex = index - visibleItemsCount + 1;\n      } else if (index > this.__virtualizer.firstVisibleIndex) {\n        // The item is already visible, scrolling is unnecessary per se. But we need to trigger iron-list to set\n        // the correct scrollTop on the scrollTarget. Scrolling to firstVisibleIndex.\n        targetIndex = this.__virtualizer.firstVisibleIndex;\n      }\n      this.__virtualizer.scrollToIndex(Math.max(0, targetIndex));\n\n      // Sometimes the item is partly below the bottom edge, detect and adjust.\n      const lastPhysicalItem = [...this.children].find(\n        (el) => !el.hidden && el.index === this.__virtualizer.lastVisibleIndex,\n      );\n      if (!lastPhysicalItem || index !== lastPhysicalItem.index) {\n        return;\n      }\n      const lastPhysicalItemRect = lastPhysicalItem.getBoundingClientRect();\n      const scrollerRect = this.getBoundingClientRect();\n      const scrollTopAdjust = lastPhysicalItemRect.bottom - scrollerRect.bottom + this._viewportTotalPaddingBottom;\n      if (scrollTopAdjust > 0) {\n        this.scrollTop += scrollTopAdjust;\n      }\n    }\n\n    /**\n     * @param {string | object} item\n     * @param {string | object} selectedItem\n     * @param {string} itemIdPath\n     * @protected\n     */\n    _isItemSelected(item, selectedItem, itemIdPath) {\n      if (item instanceof ComboBoxPlaceholder) {\n        return false;\n      } else if (itemIdPath && item !== undefined && selectedItem !== undefined) {\n        return this.get(itemIdPath, item) === this.get(itemIdPath, selectedItem);\n      }\n      return item === selectedItem;\n    }\n\n    /** @private */\n    __itemsChanged(items) {\n      if (this.__virtualizer && items) {\n        this.__virtualizer.size = items.length;\n        this.__virtualizer.flush();\n        this.requestContentUpdate();\n      }\n    }\n\n    /** @private */\n    __loadingChanged() {\n      this.requestContentUpdate();\n    }\n\n    /** @private */\n    __openedChanged(opened) {\n      if (opened) {\n        this.requestContentUpdate();\n      }\n    }\n\n    /** @private */\n    __selectedItemChanged() {\n      this.requestContentUpdate();\n    }\n\n    /** @private */\n    __focusedIndexChanged(index, oldIndex) {\n      if (index !== oldIndex) {\n        this.requestContentUpdate();\n      }\n\n      // Do not jump back to the previously focused item while loading\n      // when requesting next page from the data provider on scroll.\n      if (index >= 0 && !this.loading) {\n        this.scrollIntoView(index);\n      }\n    }\n\n    /** @private */\n    __rendererChanged(renderer, oldRenderer) {\n      if (renderer || oldRenderer) {\n        this.requestContentUpdate();\n      }\n    }\n\n    /** @private */\n    __createElements(count) {\n      return [...Array(count)].map(() => {\n        const item = document.createElement(`${this.__hostTagName}-item`);\n        item.addEventListener('click', this.__boundOnItemClick);\n        // Negative tabindex prevents the item content from being focused.\n        item.tabIndex = '-1';\n        item.style.width = '100%';\n        return item;\n      });\n    }\n\n    /**\n     * @param {HTMLElement} el\n     * @param {number} index\n     * @protected\n     */\n    _updateElement(el, index) {\n      const item = this.items[index];\n      const focusedIndex = this.focusedIndex;\n      const selected = this._isItemSelected(item, this.selectedItem, this.itemIdPath);\n\n      el.setProperties({\n        item,\n        index,\n        label: this.getItemLabel(item),\n        selected,\n        renderer: this.renderer,\n        focused: !this.loading && focusedIndex === index,\n      });\n\n      el.id = `${this.__hostTagName}-item-${index}`;\n      el.setAttribute('role', index !== undefined ? 'option' : false);\n      el.setAttribute('aria-selected', selected.toString());\n      el.setAttribute('aria-posinset', index + 1);\n      el.setAttribute('aria-setsize', this.items.length);\n\n      if (this.theme) {\n        el.setAttribute('theme', this.theme);\n      } else {\n        el.removeAttribute('theme');\n      }\n\n      if (item instanceof ComboBoxPlaceholder) {\n        this.__requestItemByIndex(index);\n      }\n    }\n\n    /** @private */\n    __onItemClick(e) {\n      this.dispatchEvent(new CustomEvent('selection-changed', { detail: { item: e.currentTarget.item } }));\n    }\n\n    /**\n     * We want to prevent the kinetic scrolling energy from being transferred from the overlay contents over to the parent.\n     * Further improvement ideas: after the contents have been scrolled to the top or bottom and scrolling has stopped, it could allow\n     * scrolling the parent similarly to touch scrolling.\n     * @private\n     */\n    __patchWheelOverScrolling() {\n      this.$.selector.addEventListener('wheel', (e) => {\n        const scrolledToTop = this.scrollTop === 0;\n        const scrolledToBottom = this.scrollHeight - this.scrollTop - this.clientHeight <= 1;\n        if (scrolledToTop && e.deltaY < 0) {\n          e.preventDefault();\n        } else if (scrolledToBottom && e.deltaY > 0) {\n          e.preventDefault();\n        }\n      });\n    }\n\n    /**\n     * Dispatches an `index-requested` event for the given index to notify\n     * the data provider that it should start loading the page containing the requested index.\n     *\n     * The event is dispatched asynchronously to prevent an immediate page request and therefore\n     * a possible infinite recursion in case the data provider implements page request cancelation logic\n     * by invoking data provider page callbacks with an empty array.\n     * The infinite recursion may occur otherwise since invoking a data provider page callback with an empty array\n     * triggers a synchronous scroller update and, if the callback corresponds to the currently visible page,\n     * the scroller will synchronously request the page again which may lead to looping in the end.\n     * That was the case for the Flow counterpart:\n     * https://github.com/vaadin/flow-components/issues/3553#issuecomment-1239344828\n     * @private\n     */\n    __requestItemByIndex(index) {\n      requestAnimationFrame(() => {\n        this.dispatchEvent(\n          new CustomEvent('index-requested', {\n            detail: {\n              index,\n              currentScrollerPos: this._oldScrollerPosition,\n            },\n          }),\n        );\n      });\n    }\n\n    /** @private */\n    _visibleItemsCount() {\n      // Ensure items are positioned\n      this.__virtualizer.scrollToIndex(this.__virtualizer.firstVisibleIndex);\n      const hasItems = this.__virtualizer.size > 0;\n      return hasItems ? this.__virtualizer.lastVisibleIndex - this.__virtualizer.firstVisibleIndex + 1 : 0;\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2018 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { ComboBoxScrollerMixin } from '@vaadin/combo-box/src/vaadin-combo-box-scroller-mixin.js';\n/**\n * An element used internally by `<vaadin-time-picker>`. Not intended to be used separately.\n *\n * @extends HTMLElement\n * @mixes ComboBoxScrollerMixin\n * @private\n */\nexport class TimePickerScroller extends ComboBoxScrollerMixin(PolymerElement) {\n  static get is() {\n    return 'vaadin-time-picker-scroller';\n  }\n\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: block;\n          min-height: 1px;\n          overflow: auto;\n\n          /* Fixes item background from getting on top of scrollbars on Safari */\n          transform: translate3d(0, 0, 0);\n\n          /* Enable momentum scrolling on iOS */\n          -webkit-overflow-scrolling: touch;\n\n          /* Fixes scrollbar disappearing when 'Show scroll bars: Always' enabled in Safari */\n          box-shadow: 0 0 0 white;\n        }\n\n        #selector {\n          border-width: var(--_vaadin-time-picker-items-container-border-width);\n          border-style: var(--_vaadin-time-picker-items-container-border-style);\n          border-color: var(--_vaadin-time-picker-items-container-border-color, transparent);\n          position: relative;\n        }\n      </style>\n      <div id=\"selector\">\n        <slot></slot>\n      </div>\n    `;\n  }\n}\n\ncustomElements.define(TimePickerScroller.is, TimePickerScroller);\n","/**\n * @license\n * Copyright (c) 2015 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { PositionMixin } from '@vaadin/overlay/src/vaadin-overlay-position-mixin.js';\n\n/**\n * @polymerMixin\n * @mixes PositionMixin\n */\nexport const ComboBoxOverlayMixin = (superClass) =>\n  class ComboBoxOverlayMixin extends PositionMixin(superClass) {\n    static get observers() {\n      return ['_setOverlayWidth(positionTarget, opened)'];\n    }\n\n    constructor() {\n      super();\n\n      this.requiredVerticalSpace = 200;\n    }\n\n    /** @protected */\n    connectedCallback() {\n      super.connectedCallback();\n\n      const comboBox = this._comboBox;\n\n      const hostDir = comboBox && comboBox.getAttribute('dir');\n      if (hostDir) {\n        this.setAttribute('dir', hostDir);\n      }\n    }\n\n    /**\n     * Override method inherited from `Overlay`\n     * to not close on position target click.\n     *\n     * @param {Event} event\n     * @return {boolean}\n     * @protected\n     */\n    _shouldCloseOnOutsideClick(event) {\n      const eventPath = event.composedPath();\n      return !eventPath.includes(this.positionTarget) && !eventPath.includes(this);\n    }\n\n    /** @private */\n    _setOverlayWidth(positionTarget, opened) {\n      if (positionTarget && opened) {\n        const propPrefix = this.localName;\n        this.style.setProperty(`--_${propPrefix}-default-width`, `${positionTarget.clientWidth}px`);\n\n        const customWidth = getComputedStyle(this._comboBox).getPropertyValue(`--${propPrefix}-width`);\n\n        if (customWidth === '') {\n          this.style.removeProperty(`--${propPrefix}-width`);\n        } else {\n          this.style.setProperty(`--${propPrefix}-width`, customWidth);\n        }\n\n        this._updatePosition();\n      }\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2018 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { ComboBoxOverlayMixin } from '@vaadin/combo-box/src/vaadin-combo-box-overlay-mixin.js';\nimport { Overlay } from '@vaadin/overlay/src/vaadin-overlay.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles(\n  'vaadin-time-picker-overlay',\n  css`\n    #overlay {\n      width: var(--vaadin-time-picker-overlay-width, var(--_vaadin-time-picker-overlay-default-width, auto));\n    }\n\n    [part='content'] {\n      display: flex;\n      flex-direction: column;\n      height: 100%;\n    }\n  `,\n  { moduleId: 'vaadin-time-picker-overlay-styles' },\n);\n\nlet memoizedTemplate;\n\n/**\n * An element used internally by `<vaadin-time-picker>`. Not intended to be used separately.\n *\n * @extends ComboBoxOverlay\n * @private\n */\nclass TimePickerOverlay extends ComboBoxOverlayMixin(Overlay) {\n  static get is() {\n    return 'vaadin-time-picker-overlay';\n  }\n\n  static get template() {\n    if (!memoizedTemplate) {\n      memoizedTemplate = super.template.cloneNode(true);\n      memoizedTemplate.content.querySelector('[part~=\"overlay\"]').removeAttribute('tabindex');\n    }\n\n    return memoizedTemplate;\n  }\n}\n\ncustomElements.define(TimePickerOverlay.is, TimePickerOverlay);\n","/**\n * @license\n * Copyright (c) 2015 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { DisabledMixin } from '@vaadin/a11y-base/src/disabled-mixin.js';\nimport { isElementFocused } from '@vaadin/a11y-base/src/focus-utils.js';\nimport { KeyboardMixin } from '@vaadin/a11y-base/src/keyboard-mixin.js';\nimport { isTouch } from '@vaadin/component-base/src/browser-utils.js';\nimport { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';\nimport { OverlayClassMixin } from '@vaadin/component-base/src/overlay-class-mixin.js';\nimport { processTemplates } from '@vaadin/component-base/src/templates.js';\nimport { InputMixin } from '@vaadin/field-base/src/input-mixin.js';\nimport { VirtualKeyboardController } from '@vaadin/field-base/src/virtual-keyboard-controller.js';\nimport { ComboBoxPlaceholder } from './vaadin-combo-box-placeholder.js';\n\n/**\n * Checks if the value is supported as an item value in this control.\n *\n * @param {unknown} value\n * @return {boolean}\n */\nfunction isValidValue(value) {\n  return value !== undefined && value !== null;\n}\n\n/**\n * Returns the index of the first item that satisfies the provided testing function\n * ignoring placeholder items.\n *\n * @param {Array<ComboBoxItem | string>} items\n * @param {Function} callback\n * @return {number}\n */\nfunction findItemIndex(items, callback) {\n  return items.findIndex((item) => {\n    if (item instanceof ComboBoxPlaceholder) {\n      return false;\n    }\n\n    return callback(item);\n  });\n}\n\n/**\n * @polymerMixin\n * @mixes ControllerMixin\n * @mixes DisabledMixin\n * @mixes InputMixin\n * @mixes KeyboardMixin\n * @mixes OverlayClassMixin\n * @param {function(new:HTMLElement)} subclass\n */\nexport const ComboBoxMixin = (subclass) =>\n  class ComboBoxMixinClass extends OverlayClassMixin(\n    ControllerMixin(KeyboardMixin(InputMixin(DisabledMixin(subclass)))),\n  ) {\n    static get properties() {\n      return {\n        /**\n         * True if the dropdown is open, false otherwise.\n         * @type {boolean}\n         */\n        opened: {\n          type: Boolean,\n          notify: true,\n          value: false,\n          reflectToAttribute: true,\n          observer: '_openedChanged',\n        },\n\n        /**\n         * Set true to prevent the overlay from opening automatically.\n         * @attr {boolean} auto-open-disabled\n         */\n        autoOpenDisabled: {\n          type: Boolean,\n        },\n\n        /**\n         * When present, it specifies that the field is read-only.\n         * @type {boolean}\n         */\n        readonly: {\n          type: Boolean,\n          value: false,\n          reflectToAttribute: true,\n        },\n\n        /**\n         * Custom function for rendering the content of every item.\n         * Receives three arguments:\n         *\n         * - `root` The `<vaadin-combo-box-item>` internal container DOM element.\n         * - `comboBox` The reference to the `<vaadin-combo-box>` element.\n         * - `model` The object with the properties related with the rendered\n         *   item, contains:\n         *   - `model.index` The index of the rendered item.\n         *   - `model.item` The item.\n         * @type {ComboBoxRenderer | undefined}\n         */\n        renderer: Function,\n\n        /**\n         * A full set of items to filter the visible options from.\n         * The items can be of either `String` or `Object` type.\n         * @type {!Array<!ComboBoxItem | string> | undefined}\n         */\n        items: {\n          type: Array,\n          observer: '_itemsChanged',\n        },\n\n        /**\n         * If `true`, the user can input a value that is not present in the items list.\n         * `value` property will be set to the input value in this case.\n         * Also, when `value` is set programmatically, the input value will be set\n         * to reflect that value.\n         * @attr {boolean} allow-custom-value\n         * @type {boolean}\n         */\n        allowCustomValue: {\n          type: Boolean,\n          value: false,\n        },\n\n        /**\n         * A subset of items, filtered based on the user input. Filtered items\n         * can be assigned directly to omit the internal filtering functionality.\n         * The items can be of either `String` or `Object` type.\n         * @type {!Array<!ComboBoxItem | string> | undefined}\n         */\n        filteredItems: {\n          type: Array,\n          observer: '_filteredItemsChanged',\n        },\n\n        /**\n         * Used to detect user value changes and fire `change` events.\n         * @private\n         */\n        _lastCommittedValue: String,\n\n        /**\n         * When set to `true`, \"loading\" attribute is added to host and the overlay element.\n         * @type {boolean}\n         */\n        loading: {\n          type: Boolean,\n          value: false,\n          reflectToAttribute: true,\n        },\n\n        /**\n         * @type {number}\n         * @protected\n         */\n        _focusedIndex: {\n          type: Number,\n          observer: '_focusedIndexChanged',\n          value: -1,\n        },\n\n        /**\n         * Filtering string the user has typed into the input field.\n         * @type {string}\n         */\n        filter: {\n          type: String,\n          value: '',\n          notify: true,\n        },\n\n        /**\n         * The selected item from the `items` array.\n         * @type {ComboBoxItem | string | undefined}\n         */\n        selectedItem: {\n          type: Object,\n          notify: true,\n        },\n\n        /**\n         * Path for label of the item. If `items` is an array of objects, the\n         * `itemLabelPath` is used to fetch the displayed string label for each\n         * item.\n         *\n         * The item label is also used for matching items when processing user\n         * input, i.e., for filtering and selecting items.\n         * @attr {string} item-label-path\n         * @type {string}\n         */\n        itemLabelPath: {\n          type: String,\n          value: 'label',\n          observer: '_itemLabelPathChanged',\n        },\n\n        /**\n         * Path for the value of the item. If `items` is an array of objects, the\n         * `itemValuePath:` is used to fetch the string value for the selected\n         * item.\n         *\n         * The item value is used in the `value` property of the combo box,\n         * to provide the form value.\n         * @attr {string} item-value-path\n         * @type {string}\n         */\n        itemValuePath: {\n          type: String,\n          value: 'value',\n        },\n\n        /**\n         * Path for the id of the item. If `items` is an array of objects,\n         * the `itemIdPath` is used to compare and identify the same item\n         * in `selectedItem` and `filteredItems` (items given by the\n         * `dataProvider` callback).\n         * @attr {string} item-id-path\n         */\n        itemIdPath: String,\n\n        /**\n         * @type {!HTMLElement | undefined}\n         * @protected\n         */\n        _toggleElement: {\n          type: Object,\n          observer: '_toggleElementChanged',\n        },\n\n        /** @private */\n        _closeOnBlurIsPrevented: Boolean,\n\n        /** @private */\n        _scroller: Object,\n\n        /** @private */\n        _overlayOpened: {\n          type: Boolean,\n          observer: '_overlayOpenedChanged',\n        },\n      };\n    }\n\n    static get observers() {\n      return [\n        '_selectedItemChanged(selectedItem, itemValuePath, itemLabelPath)',\n        '_openedOrItemsChanged(opened, filteredItems, loading)',\n        '_updateScroller(_scroller, filteredItems, opened, loading, selectedItem, itemIdPath, _focusedIndex, renderer, theme)',\n      ];\n    }\n\n    constructor() {\n      super();\n      this._boundOnFocusout = this._onFocusout.bind(this);\n      this._boundOverlaySelectedItemChanged = this._overlaySelectedItemChanged.bind(this);\n      this._boundOnClearButtonMouseDown = this.__onClearButtonMouseDown.bind(this);\n      this._boundOnClick = this._onClick.bind(this);\n      this._boundOnOverlayTouchAction = this._onOverlayTouchAction.bind(this);\n      this._boundOnTouchend = this._onTouchend.bind(this);\n    }\n\n    /**\n     * Tag name prefix used by scroller and items.\n     * @protected\n     * @return {string}\n     */\n    get _tagNamePrefix() {\n      return 'vaadin-combo-box';\n    }\n\n    /**\n     * Get a reference to the native `<input>` element.\n     * Override to provide a custom input.\n     * @protected\n     * @return {HTMLInputElement | undefined}\n     */\n    get _nativeInput() {\n      return this.inputElement;\n    }\n\n    /**\n     * Override method inherited from `InputMixin`\n     * to customize the input element.\n     * @protected\n     * @override\n     */\n    _inputElementChanged(inputElement) {\n      super._inputElementChanged(inputElement);\n\n      const input = this._nativeInput;\n\n      if (input) {\n        input.autocomplete = 'off';\n        input.autocapitalize = 'off';\n\n        input.setAttribute('role', 'combobox');\n        input.setAttribute('aria-autocomplete', 'list');\n        input.setAttribute('aria-expanded', !!this.opened);\n\n        // Disable the macOS Safari spell check auto corrections.\n        input.setAttribute('spellcheck', 'false');\n\n        // Disable iOS autocorrect suggestions.\n        input.setAttribute('autocorrect', 'off');\n\n        this._revertInputValueToValue();\n\n        if (this.clearElement) {\n          this.clearElement.addEventListener('mousedown', this._boundOnClearButtonMouseDown);\n        }\n      }\n    }\n\n    /** @protected */\n    ready() {\n      super.ready();\n\n      this._initOverlay();\n      this._initScroller();\n\n      this.addEventListener('focusout', this._boundOnFocusout);\n\n      this._lastCommittedValue = this.value;\n\n      this.addEventListener('click', this._boundOnClick);\n      this.addEventListener('touchend', this._boundOnTouchend);\n\n      const bringToFrontListener = () => {\n        requestAnimationFrame(() => {\n          this._overlayElement.bringToFront();\n        });\n      };\n\n      this.addEventListener('mousedown', bringToFrontListener);\n      this.addEventListener('touchstart', bringToFrontListener);\n\n      processTemplates(this);\n\n      this.addController(new VirtualKeyboardController(this));\n    }\n\n    /** @protected */\n    disconnectedCallback() {\n      super.disconnectedCallback();\n\n      // Close the overlay on detach\n      this.close();\n    }\n\n    /**\n     * Requests an update for the content of items.\n     * While performing the update, it invokes the renderer (passed in the `renderer` property) once an item.\n     *\n     * It is not guaranteed that the update happens immediately (synchronously) after it is requested.\n     */\n    requestContentUpdate() {\n      if (!this._scroller) {\n        return;\n      }\n\n      this._scroller.requestContentUpdate();\n\n      this._getItemElements().forEach((item) => {\n        item.requestContentUpdate();\n      });\n    }\n\n    /**\n     * Opens the dropdown list.\n     */\n    open() {\n      // Prevent _open() being called when input is disabled or read-only\n      if (!this.disabled && !this.readonly) {\n        this.opened = true;\n      }\n    }\n\n    /**\n     * Closes the dropdown list.\n     */\n    close() {\n      this.opened = false;\n    }\n\n    /**\n     * Override Polymer lifecycle callback to handle `filter` property change after\n     * the observer for `opened` property is triggered. This is needed when opening\n     * combo-box on user input to ensure the focused index is set correctly.\n     *\n     * @param {!Object} currentProps Current accessor values\n     * @param {?Object} changedProps Properties changed since the last call\n     * @param {?Object} oldProps Previous values for each changed property\n     * @protected\n     * @override\n     */\n    _propertiesChanged(currentProps, changedProps, oldProps) {\n      super._propertiesChanged(currentProps, changedProps, oldProps);\n\n      if (changedProps.filter !== undefined) {\n        this._filterChanged(changedProps.filter);\n      }\n    }\n\n    /** @private */\n    _initOverlay() {\n      const overlay = this.$.overlay;\n\n      // Store instance for detecting \"dir\" attribute on opening\n      overlay._comboBox = this;\n\n      overlay.addEventListener('touchend', this._boundOnOverlayTouchAction);\n      overlay.addEventListener('touchmove', this._boundOnOverlayTouchAction);\n\n      // Prevent blurring the input when clicking inside the overlay\n      overlay.addEventListener('mousedown', (e) => e.preventDefault());\n\n      // Manual two-way binding for the overlay \"opened\" property\n      overlay.addEventListener('opened-changed', (e) => {\n        this._overlayOpened = e.detail.value;\n      });\n\n      this._overlayElement = overlay;\n    }\n\n    /**\n     * Create and initialize the scroller element.\n     * Override to provide custom host reference.\n     *\n     * @protected\n     */\n    _initScroller(host) {\n      const scrollerTag = `${this._tagNamePrefix}-scroller`;\n\n      const overlay = this._overlayElement;\n\n      overlay.renderer = (root) => {\n        if (!root.firstChild) {\n          root.appendChild(document.createElement(scrollerTag));\n        }\n      };\n\n      // Ensure the scroller is rendered\n      overlay.requestContentUpdate();\n\n      const scroller = overlay.querySelector(scrollerTag);\n\n      scroller.owner = host || this;\n      scroller.getItemLabel = this._getItemLabel.bind(this);\n      scroller.addEventListener('selection-changed', this._boundOverlaySelectedItemChanged);\n\n      // Trigger the observer to set properties\n      this._scroller = scroller;\n    }\n\n    /** @private */\n    // eslint-disable-next-line max-params\n    _updateScroller(scroller, items, opened, loading, selectedItem, itemIdPath, focusedIndex, renderer, theme) {\n      if (scroller) {\n        if (opened) {\n          scroller.style.maxHeight =\n            getComputedStyle(this).getPropertyValue(`--${this._tagNamePrefix}-overlay-max-height`) || '65vh';\n        }\n\n        scroller.setProperties({\n          items: opened ? items : [],\n          opened,\n          loading,\n          selectedItem,\n          itemIdPath,\n          focusedIndex,\n          renderer,\n          theme,\n        });\n      }\n    }\n\n    /** @private */\n    _openedOrItemsChanged(opened, items, loading) {\n      // Close the overlay if there are no items to display.\n      // See https://github.com/vaadin/vaadin-combo-box/pull/964\n      this._overlayOpened = !!(opened && (loading || (items && items.length)));\n    }\n\n    /** @private */\n    _overlayOpenedChanged(opened, wasOpened) {\n      if (opened) {\n        this.dispatchEvent(new CustomEvent('vaadin-combo-box-dropdown-opened', { bubbles: true, composed: true }));\n\n        this._onOpened();\n      } else if (wasOpened && this.filteredItems && this.filteredItems.length) {\n        this.close();\n\n        this.dispatchEvent(new CustomEvent('vaadin-combo-box-dropdown-closed', { bubbles: true, composed: true }));\n      }\n    }\n\n    /** @private */\n    _focusedIndexChanged(index, oldIndex) {\n      if (oldIndex === undefined) {\n        return;\n      }\n      this._updateActiveDescendant(index);\n    }\n\n    /** @protected */\n    _isInputFocused() {\n      return this.inputElement && isElementFocused(this.inputElement);\n    }\n\n    /** @private */\n    _updateActiveDescendant(index) {\n      const input = this._nativeInput;\n      if (!input) {\n        return;\n      }\n\n      const item = this._getItemElements().find((el) => el.index === index);\n      if (item) {\n        input.setAttribute('aria-activedescendant', item.id);\n      } else {\n        input.removeAttribute('aria-activedescendant');\n      }\n    }\n\n    /** @private */\n    _openedChanged(opened, wasOpened) {\n      // Prevent _close() being called when opened is set to its default value (false).\n      if (wasOpened === undefined) {\n        return;\n      }\n\n      if (opened) {\n        this._openedWithFocusRing = this.hasAttribute('focus-ring');\n        // For touch devices, we don't want to popup virtual keyboard\n        // unless input element is explicitly focused by the user.\n        if (!this._isInputFocused() && !isTouch) {\n          if (this.inputElement) {\n            this.inputElement.focus();\n          }\n        }\n\n        this._overlayElement.restoreFocusOnClose = true;\n      } else {\n        this._onClosed();\n        if (this._openedWithFocusRing && this._isInputFocused()) {\n          this.setAttribute('focus-ring', '');\n        }\n      }\n\n      const input = this._nativeInput;\n      if (input) {\n        input.setAttribute('aria-expanded', !!opened);\n\n        if (opened) {\n          input.setAttribute('aria-controls', this._scroller.id);\n        } else {\n          input.removeAttribute('aria-controls');\n        }\n      }\n    }\n\n    /** @private */\n    _onOverlayTouchAction() {\n      // On touch devices, blur the input on touch start inside the overlay, in order to hide\n      // the virtual keyboard. But don't close the overlay on this blur.\n      this._closeOnBlurIsPrevented = true;\n      this.inputElement.blur();\n      this._closeOnBlurIsPrevented = false;\n    }\n\n    /** @protected */\n    _isClearButton(event) {\n      return event.composedPath()[0] === this.clearElement;\n    }\n\n    /** @private */\n    __onClearButtonMouseDown(event) {\n      event.preventDefault(); // Prevent native focusout event\n      this.inputElement.focus();\n    }\n\n    /**\n     * @param {Event} event\n     * @protected\n     */\n    _onClearButtonClick(event) {\n      event.preventDefault();\n      this._onClearAction();\n\n      // De-select dropdown item\n      if (this.opened) {\n        this.requestContentUpdate();\n      }\n    }\n\n    /**\n     * @param {Event} event\n     * @private\n     */\n    _onToggleButtonClick(event) {\n      // Prevent parent components such as `vaadin-grid`\n      // from handling the click event after it bubbles.\n      event.preventDefault();\n\n      if (this.opened) {\n        this.close();\n      } else {\n        this.open();\n      }\n    }\n\n    /**\n     * @param {Event} event\n     * @protected\n     */\n    _onHostClick(event) {\n      if (!this.autoOpenDisabled) {\n        event.preventDefault();\n        this.open();\n      }\n    }\n\n    /** @private */\n    _onClick(event) {\n      if (this._isClearButton(event)) {\n        this._onClearButtonClick(event);\n      } else if (event.composedPath().includes(this._toggleElement)) {\n        this._onToggleButtonClick(event);\n      } else {\n        this._onHostClick(event);\n      }\n    }\n\n    /**\n     * Override an event listener from `KeyboardMixin`.\n     *\n     * @param {KeyboardEvent} e\n     * @protected\n     * @override\n     */\n    _onKeyDown(e) {\n      super._onKeyDown(e);\n\n      if (e.key === 'Tab') {\n        this._overlayElement.restoreFocusOnClose = false;\n      } else if (e.key === 'ArrowDown') {\n        this._onArrowDown();\n\n        // Prevent caret from moving\n        e.preventDefault();\n      } else if (e.key === 'ArrowUp') {\n        this._onArrowUp();\n\n        // Prevent caret from moving\n        e.preventDefault();\n      }\n    }\n\n    /** @private */\n    _getItemLabel(item) {\n      let label = item && this.itemLabelPath ? this.get(this.itemLabelPath, item) : undefined;\n      if (label === undefined || label === null) {\n        label = item ? item.toString() : '';\n      }\n      return label;\n    }\n\n    /** @private */\n    _getItemValue(item) {\n      let value = item && this.itemValuePath ? this.get(this.itemValuePath, item) : undefined;\n      if (value === undefined) {\n        value = item ? item.toString() : '';\n      }\n      return value;\n    }\n\n    /** @private */\n    _onArrowDown() {\n      if (this.opened) {\n        const items = this.filteredItems;\n        if (items) {\n          this._focusedIndex = Math.min(items.length - 1, this._focusedIndex + 1);\n          this._prefillFocusedItemLabel();\n        }\n      } else {\n        this.open();\n      }\n    }\n\n    /** @private */\n    _onArrowUp() {\n      if (this.opened) {\n        if (this._focusedIndex > -1) {\n          this._focusedIndex = Math.max(0, this._focusedIndex - 1);\n        } else {\n          const items = this.filteredItems;\n          if (items) {\n            this._focusedIndex = items.length - 1;\n          }\n        }\n\n        this._prefillFocusedItemLabel();\n      } else {\n        this.open();\n      }\n    }\n\n    /** @private */\n    _prefillFocusedItemLabel() {\n      if (this._focusedIndex > -1) {\n        const focusedItem = this.filteredItems[this._focusedIndex];\n        this._inputElementValue = this._getItemLabel(focusedItem);\n        this._markAllSelectionRange();\n      }\n    }\n\n    /** @private */\n    _setSelectionRange(start, end) {\n      // Setting selection range focuses and/or moves the caret in some browsers,\n      // and there's no need to modify the selection range if the input isn't focused anyway.\n      // This affects Safari. When the overlay is open, and then hitting tab, browser should focus\n      // the next focusable element instead of the combo-box itself.\n      if (this._isInputFocused() && this.inputElement.setSelectionRange) {\n        this.inputElement.setSelectionRange(start, end);\n      }\n    }\n\n    /** @private */\n    _markAllSelectionRange() {\n      if (this._inputElementValue !== undefined) {\n        this._setSelectionRange(0, this._inputElementValue.length);\n      }\n    }\n\n    /** @private */\n    _clearSelectionRange() {\n      if (this._inputElementValue !== undefined) {\n        const pos = this._inputElementValue ? this._inputElementValue.length : 0;\n        this._setSelectionRange(pos, pos);\n      }\n    }\n\n    /** @private */\n    _closeOrCommit() {\n      if (!this.opened && !this.loading) {\n        this._commitValue();\n      } else {\n        this.close();\n      }\n    }\n\n    /**\n     * Override an event listener from `KeyboardMixin`.\n     *\n     * @param {KeyboardEvent} e\n     * @protected\n     * @override\n     */\n    _onEnter(e) {\n      // Do not commit value when custom values are disallowed and input value is not a valid option\n      // also stop propagation of the event, otherwise the user could submit a form while the input\n      // still contains an invalid value\n      const hasInvalidOption =\n        this._focusedIndex < 0 &&\n        this._inputElementValue !== '' &&\n        this._getItemLabel(this.selectedItem) !== this._inputElementValue;\n      if (!this.allowCustomValue && hasInvalidOption) {\n        // Do not submit the surrounding form.\n        e.preventDefault();\n        // Do not trigger global listeners\n        e.stopPropagation();\n        return;\n      }\n\n      // Stop propagation of the enter event only if the dropdown is opened, this\n      // \"consumes\" the enter event for the action of closing the dropdown\n      if (this.opened) {\n        // Do not submit the surrounding form.\n        e.preventDefault();\n        // Do not trigger global listeners\n        e.stopPropagation();\n      }\n\n      this._closeOrCommit();\n    }\n\n    /**\n     * Override an event listener from `KeyboardMixin`.\n     * Do not call `super` in order to override clear\n     * button logic defined in `InputControlMixin`.\n     *\n     * @param {!KeyboardEvent} e\n     * @protected\n     * @override\n     */\n    _onEscape(e) {\n      if (this.autoOpenDisabled) {\n        // Auto-open is disabled\n        if (this.opened || (this.value !== this._inputElementValue && this._inputElementValue.length > 0)) {\n          // The overlay is open or\n          // The input value has changed but the change hasn't been committed, so cancel it.\n          e.stopPropagation();\n          this._focusedIndex = -1;\n          this.cancel();\n        } else if (this.clearButtonVisible && !this.opened && !!this.value) {\n          e.stopPropagation();\n          // The clear button is visible and the overlay is closed, so clear the value.\n          this._onClearAction();\n        }\n      } else if (this.opened) {\n        // Auto-open is enabled\n        // The overlay is open\n        e.stopPropagation();\n\n        if (this._focusedIndex > -1) {\n          // An item is focused, revert the input to the filtered value\n          this._focusedIndex = -1;\n          this._revertInputValue();\n        } else {\n          // No item is focused, cancel the change and close the overlay\n          this.cancel();\n        }\n      } else if (this.clearButtonVisible && !!this.value) {\n        e.stopPropagation();\n        // The clear button is visible and the overlay is closed, so clear the value.\n        this._onClearAction();\n      }\n    }\n\n    /** @private */\n    _toggleElementChanged(toggleElement) {\n      if (toggleElement) {\n        // Don't blur the input on toggle mousedown\n        toggleElement.addEventListener('mousedown', (e) => e.preventDefault());\n        // Unfocus previously focused element if focus is not inside combo box (on touch devices)\n        toggleElement.addEventListener('click', () => {\n          if (isTouch && !this._isInputFocused()) {\n            document.activeElement.blur();\n          }\n        });\n      }\n    }\n\n    /**\n     * Clears the current value.\n     * @protected\n     */\n    _onClearAction() {\n      this.selectedItem = null;\n\n      if (this.allowCustomValue) {\n        this.value = '';\n      }\n\n      this._detectAndDispatchChange();\n    }\n\n    /**\n     * Reverts back to original value.\n     */\n    cancel() {\n      this._revertInputValueToValue();\n      // In the next _detectAndDispatchChange() call, the change detection should not pass\n      this._lastCommittedValue = this.value;\n      this._closeOrCommit();\n    }\n\n    /** @private */\n    _onOpened() {\n      // _detectAndDispatchChange() should not consider value changes done before opening\n      this._lastCommittedValue = this.value;\n    }\n\n    /** @private */\n    _onClosed() {\n      if (!this.loading || this.allowCustomValue) {\n        this._commitValue();\n      }\n    }\n\n    /** @private */\n    _commitValue() {\n      if (this._focusedIndex > -1) {\n        const focusedItem = this.filteredItems[this._focusedIndex];\n        if (this.selectedItem !== focusedItem) {\n          this.selectedItem = focusedItem;\n        }\n        // Make sure input field is updated in case value doesn't change (i.e. FOO -> foo)\n        this._inputElementValue = this._getItemLabel(this.selectedItem);\n        this._focusedIndex = -1;\n      } else if (this._inputElementValue === '' || this._inputElementValue === undefined) {\n        this.selectedItem = null;\n\n        if (this.allowCustomValue) {\n          this.value = '';\n        }\n      } else {\n        // Try to find an item which label matches the input value.\n        const items = [...(this.filteredItems || []), this.selectedItem];\n        const itemMatchingInputValue = items[this.__getItemIndexByLabel(items, this._inputElementValue)];\n\n        if (\n          this.allowCustomValue &&\n          // To prevent a repetitive input value being saved after pressing ESC and Tab.\n          !itemMatchingInputValue\n        ) {\n          const customValue = this._inputElementValue;\n\n          // Store reference to the last custom value for checking it on focusout.\n          this._lastCustomValue = customValue;\n\n          // An item matching by label was not found, but custom values are allowed.\n          // Dispatch a custom-value-set event with the input value.\n          const e = new CustomEvent('custom-value-set', {\n            detail: customValue,\n            composed: true,\n            cancelable: true,\n            bubbles: true,\n          });\n          this.dispatchEvent(e);\n          if (!e.defaultPrevented) {\n            this.value = customValue;\n          }\n        } else if (!this.allowCustomValue && !this.opened && itemMatchingInputValue) {\n          // An item matching by label was found, select it.\n          this.value = this._getItemValue(itemMatchingInputValue);\n        } else {\n          // Revert the input value\n          this._inputElementValue = this.selectedItem ? this._getItemLabel(this.selectedItem) : this.value || '';\n        }\n      }\n\n      this._detectAndDispatchChange();\n\n      this._clearSelectionRange();\n\n      this.filter = '';\n    }\n\n    /**\n     * Override an event listener from `InputMixin`.\n     * @param {!Event} event\n     * @protected\n     * @override\n     */\n    _onInput(event) {\n      const filter = this._inputElementValue;\n\n      // When opening dropdown on user input, both `opened` and `filter` properties are set.\n      // Perform a batched property update instead of relying on sync property observers.\n      // This is necessary to avoid an extra data-provider request for loading first page.\n      const props = {};\n\n      if (this.filter === filter) {\n        // Filter and input value might get out of sync, while keyboard navigating for example.\n        // Afterwards, input value might be changed to the same value as used in filtering.\n        // In situation like these, we need to make sure all the filter changes handlers are run.\n        this._filterChanged(this.filter);\n      } else {\n        props.filter = filter;\n      }\n\n      if (!this.opened && !this._isClearButton(event) && !this.autoOpenDisabled) {\n        props.opened = true;\n      }\n\n      this.setProperties(props);\n    }\n\n    /**\n     * Override an event listener from `InputMixin`.\n     * @param {!Event} event\n     * @protected\n     * @override\n     */\n    _onChange(event) {\n      // Suppress the native change event fired on the native input.\n      // We use `_detectAndDispatchChange` to fire a custom event.\n      event.stopPropagation();\n    }\n\n    /** @private */\n    _itemLabelPathChanged(itemLabelPath) {\n      if (typeof itemLabelPath !== 'string') {\n        console.error('You should set itemLabelPath to a valid string');\n      }\n    }\n\n    /** @private */\n    _filterChanged(filter) {\n      // Scroll to the top of the list whenever the filter changes.\n      this._scrollIntoView(0);\n\n      this._focusedIndex = -1;\n\n      if (this.items) {\n        this.filteredItems = this._filterItems(this.items, filter);\n      } else {\n        // With certain use cases (e. g., external filtering), `items` are\n        // undefined. Filtering is unnecessary per se, but the filteredItems\n        // observer should still be invoked to update focused item.\n        this._filteredItemsChanged(this.filteredItems);\n      }\n    }\n\n    /** @protected */\n    _revertInputValue() {\n      if (this.filter !== '') {\n        this._inputElementValue = this.filter;\n      } else {\n        this._revertInputValueToValue();\n      }\n      this._clearSelectionRange();\n    }\n\n    /** @private */\n    _revertInputValueToValue() {\n      if (this.allowCustomValue && !this.selectedItem) {\n        this._inputElementValue = this.value;\n      } else {\n        this._inputElementValue = this._getItemLabel(this.selectedItem);\n      }\n    }\n\n    /** @private */\n    _selectedItemChanged(selectedItem) {\n      if (selectedItem === null || selectedItem === undefined) {\n        if (this.filteredItems) {\n          if (!this.allowCustomValue) {\n            this.value = '';\n          }\n\n          this._toggleHasValue(this._hasValue);\n          this._inputElementValue = this.value;\n        }\n      } else {\n        const value = this._getItemValue(selectedItem);\n        if (this.value !== value) {\n          this.value = value;\n          if (this.value !== value) {\n            // The value was changed to something else in value-changed listener,\n            // so prevent from resetting it to the previous value.\n            return;\n          }\n        }\n\n        this._toggleHasValue(true);\n        this._inputElementValue = this._getItemLabel(selectedItem);\n      }\n    }\n\n    /**\n     * Override an observer from `InputMixin`.\n     * @protected\n     * @override\n     */\n    _valueChanged(value, oldVal) {\n      if (value === '' && oldVal === undefined) {\n        // Initializing, no need to do anything\n        // See https://github.com/vaadin/vaadin-combo-box/issues/554\n        return;\n      }\n\n      if (isValidValue(value)) {\n        if (this._getItemValue(this.selectedItem) !== value) {\n          this._selectItemForValue(value);\n        }\n\n        if (!this.selectedItem && this.allowCustomValue) {\n          this._inputElementValue = value;\n        }\n\n        this._toggleHasValue(this._hasValue);\n      } else {\n        this.selectedItem = null;\n      }\n\n      this.filter = '';\n\n      // In the next _detectAndDispatchChange() call, the change detection should pass\n      this._lastCommittedValue = undefined;\n    }\n\n    /** @private */\n    _detectAndDispatchChange() {\n      if (this.value !== this._lastCommittedValue) {\n        this.dispatchEvent(new CustomEvent('change', { bubbles: true }));\n        this._lastCommittedValue = this.value;\n      }\n    }\n\n    /** @private */\n    _itemsChanged(items, oldItems) {\n      this._ensureItemsOrDataProvider(() => {\n        this.items = oldItems;\n      });\n\n      if (items) {\n        this.filteredItems = items.slice(0);\n      } else if (oldItems) {\n        // Only clear filteredItems if the component had items previously but got cleared\n        this.filteredItems = null;\n      }\n    }\n\n    /** @private */\n    _filteredItemsChanged(filteredItems, oldFilteredItems) {\n      // Store the currently focused item if any. The focused index preserves\n      // in the case when more filtered items are loading but it is reset\n      // when the user types in a filter query.\n      const focusedItem = oldFilteredItems ? oldFilteredItems[this._focusedIndex] : null;\n\n      // Try to sync `selectedItem` based on `value` once a new set of `filteredItems` is available\n      // (as a result of external filtering or when they have been loaded by the data provider).\n      // When `value` is specified but `selectedItem` is not, it means that there was no item\n      // matching `value` at the moment `value` was set, so `selectedItem` has remained unsynced.\n      const valueIndex = this.__getItemIndexByValue(filteredItems, this.value);\n      if ((this.selectedItem === null || this.selectedItem === undefined) && valueIndex >= 0) {\n        this.selectedItem = filteredItems[valueIndex];\n      }\n\n      // Try to first set focus on the item that had been focused before `filteredItems` were updated\n      // if it is still present in the `filteredItems` array. Otherwise, set the focused index\n      // depending on the selected item or the filter query.\n      const focusedItemIndex = this.__getItemIndexByValue(filteredItems, this._getItemValue(focusedItem));\n      if (focusedItemIndex > -1) {\n        this._focusedIndex = focusedItemIndex;\n      } else {\n        // When the user filled in something that is different from the current value = filtering is enabled,\n        // set the focused index to the item that matches the filter query.\n        this._focusedIndex = this.__getItemIndexByLabel(this.filteredItems, this.filter);\n      }\n    }\n\n    /** @private */\n    _filterItems(arr, filter) {\n      if (!arr) {\n        return arr;\n      }\n\n      const filteredItems = arr.filter((item) => {\n        filter = filter ? filter.toString().toLowerCase() : '';\n        // Check if item contains input value.\n        return this._getItemLabel(item).toString().toLowerCase().indexOf(filter) > -1;\n      });\n\n      return filteredItems;\n    }\n\n    /** @private */\n    _selectItemForValue(value) {\n      const valueIndex = this.__getItemIndexByValue(this.filteredItems, value);\n      const previouslySelectedItem = this.selectedItem;\n\n      if (valueIndex >= 0) {\n        this.selectedItem = this.filteredItems[valueIndex];\n      } else if (this.dataProvider && this.selectedItem === undefined) {\n        this.selectedItem = undefined;\n      } else {\n        this.selectedItem = null;\n      }\n\n      if (this.selectedItem === null && previouslySelectedItem === null) {\n        this._selectedItemChanged(this.selectedItem);\n      }\n    }\n\n    /** @private */\n    _getItemElements() {\n      return Array.from(this._scroller.querySelectorAll(`${this._tagNamePrefix}-item`));\n    }\n\n    /** @private */\n    _scrollIntoView(index) {\n      if (!this._scroller) {\n        return;\n      }\n      this._scroller.scrollIntoView(index);\n    }\n\n    /**\n     * Returns the first item that matches the provided value.\n     *\n     * @private\n     */\n    __getItemIndexByValue(items, value) {\n      if (!items || !isValidValue(value)) {\n        return -1;\n      }\n\n      return findItemIndex(items, (item) => {\n        return this._getItemValue(item) === value;\n      });\n    }\n\n    /**\n     * Returns the first item that matches the provided label.\n     * Labels are matched against each other case insensitively.\n     *\n     * @private\n     */\n    __getItemIndexByLabel(items, label) {\n      if (!items || !label) {\n        return -1;\n      }\n\n      return findItemIndex(items, (item) => {\n        return this._getItemLabel(item).toString().toLowerCase() === label.toString().toLowerCase();\n      });\n    }\n\n    /** @private */\n    _overlaySelectedItemChanged(e) {\n      // Stop this private event from leaking outside.\n      e.stopPropagation();\n\n      if (e.detail.item instanceof ComboBoxPlaceholder) {\n        // Placeholder items should not be selectable.\n        return;\n      }\n\n      if (this.opened) {\n        this._focusedIndex = this.filteredItems.indexOf(e.detail.item);\n        this.close();\n      }\n    }\n\n    /** @private */\n    _onFocusout(event) {\n      // VoiceOver on iOS fires `focusout` event when moving focus to the item in the dropdown.\n      // Do not focus the input in this case, because it would break announcement for the item.\n      if (event.relatedTarget && event.relatedTarget.localName === `${this._tagNamePrefix}-item`) {\n        return;\n      }\n\n      // Fixes the problem with `focusout` happening when clicking on the scroll bar on Edge\n      if (event.relatedTarget === this._overlayElement) {\n        event.composedPath()[0].focus();\n        return;\n      }\n      if (!this.readonly && !this._closeOnBlurIsPrevented) {\n        // User's logic in `custom-value-set` event listener might cause input to blur,\n        // which will result in attempting to commit the same custom value once again.\n        if (!this.opened && this.allowCustomValue && this._inputElementValue === this._lastCustomValue) {\n          delete this._lastCustomValue;\n          return;\n        }\n\n        this._closeOrCommit();\n      }\n    }\n\n    /** @private */\n    _onTouchend(event) {\n      if (!this.clearElement || event.composedPath()[0] !== this.clearElement) {\n        return;\n      }\n\n      event.preventDefault();\n      this._onClearAction();\n    }\n\n    /**\n     * Fired when the value changes.\n     *\n     * @event value-changed\n     * @param {Object} detail\n     * @param {String} detail.value the combobox value\n     */\n\n    /**\n     * Fired when selected item changes.\n     *\n     * @event selected-item-changed\n     * @param {Object} detail\n     * @param {Object|String} detail.value the selected item. Type is the same as the type of `items`.\n     */\n\n    /**\n     * Fired when the user sets a custom value.\n     * @event custom-value-set\n     * @param {String} detail the custom value\n     */\n\n    /**\n     * Fired when value changes.\n     * To comply with https://developer.mozilla.org/en-US/docs/Web/Events/change\n     * @event change\n     */\n\n    /**\n     * Fired after the `vaadin-combo-box-overlay` opens.\n     *\n     * @event vaadin-combo-box-dropdown-opened\n     */\n\n    /**\n     * Fired after the `vaadin-combo-box-overlay` closes.\n     *\n     * @event vaadin-combo-box-dropdown-closed\n     */\n  };\n","/**\n * @license\n * Copyright (c) 2018 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport './vaadin-time-picker-item.js';\nimport './vaadin-time-picker-scroller.js';\nimport './vaadin-time-picker-overlay.js';\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { ComboBoxMixin } from '@vaadin/combo-box/src/vaadin-combo-box-mixin.js';\nimport { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\n/**\n * An element used internally by `<vaadin-time-picker>`. Not intended to be used separately.\n *\n * @extends HTMLElement\n * @mixes ComboBoxMixin\n * @mixes ThemableMixin\n * @private\n */\nclass TimePickerComboBox extends ComboBoxMixin(ThemableMixin(PolymerElement)) {\n  static get is() {\n    return 'vaadin-time-picker-combo-box';\n  }\n\n  static get template() {\n    return html`\n      <style>\n        :host([opened]) {\n          pointer-events: auto;\n        }\n      </style>\n\n      <slot></slot>\n\n      <vaadin-time-picker-overlay\n        id=\"overlay\"\n        opened=\"[[_overlayOpened]]\"\n        loading$=\"[[loading]]\"\n        theme$=\"[[_theme]]\"\n        position-target=\"[[positionTarget]]\"\n        no-vertical-overlap\n        restore-focus-node=\"[[inputElement]]\"\n      ></vaadin-time-picker-overlay>\n    `;\n  }\n\n  static get properties() {\n    return {\n      positionTarget: {\n        type: Object,\n      },\n    };\n  }\n\n  /**\n   * Tag name prefix used by scroller and items.\n   * @protected\n   * @return {string}\n   */\n  get _tagNamePrefix() {\n    return 'vaadin-time-picker';\n  }\n\n  /**\n   * Reference to the clear button element.\n   * @protected\n   * @return {!HTMLElement}\n   */\n  get clearElement() {\n    return this.querySelector('[part=\"clear-button\"]');\n  }\n\n  /**\n   * @override\n   * @protected\n   */\n  get _inputElementValue() {\n    return super._inputElementValue;\n  }\n\n  /**\n   * The setter is overridden to ensure the `_hasInputValue` property\n   * doesn't wrongly indicate true after the input element's value\n   * is reverted or cleared programmatically.\n   *\n   * @override\n   * @protected\n   */\n  set _inputElementValue(value) {\n    super._inputElementValue = value;\n    this._hasInputValue = value.length > 0;\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n\n    this.allowCustomValue = true;\n    this._toggleElement = this.querySelector('.toggle-button');\n\n    // See https://github.com/vaadin/vaadin-time-picker/issues/145\n    this.setAttribute('dir', 'ltr');\n  }\n}\n\ncustomElements.define(TimePickerComboBox.is, TimePickerComboBox);\n","/**\n * @license\n * Copyright (c) 2021 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { InputConstraintsMixin } from './input-constraints-mixin.js';\n\n/**\n * A mixin to provide `pattern` property.\n *\n * @polymerMixin\n * @mixes InputConstraintsMixin\n */\nexport const PatternMixin = (superclass) =>\n  class PatternMixinClass extends InputConstraintsMixin(superclass) {\n    static get properties() {\n      return {\n        /**\n         * A regular expression that the value is checked against.\n         * The pattern must match the entire value, not just some subset.\n         */\n        pattern: {\n          type: String,\n        },\n      };\n    }\n\n    static get delegateAttrs() {\n      return [...super.delegateAttrs, 'pattern'];\n    }\n\n    static get constraints() {\n      return [...super.constraints, 'pattern'];\n    }\n  };\n","/**\n * @license\n * Copyright (c) 2018 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport '@vaadin/input-container/src/vaadin-input-container.js';\nimport './vaadin-time-picker-combo-box.js';\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { ElementMixin } from '@vaadin/component-base/src/element-mixin.js';\nimport { TooltipController } from '@vaadin/component-base/src/tooltip-controller.js';\nimport { InputControlMixin } from '@vaadin/field-base/src/input-control-mixin.js';\nimport { InputController } from '@vaadin/field-base/src/input-controller.js';\nimport { LabelledInputController } from '@vaadin/field-base/src/labelled-input-controller.js';\nimport { PatternMixin } from '@vaadin/field-base/src/pattern-mixin.js';\nimport { inputFieldShared } from '@vaadin/field-base/src/styles/input-field-shared-styles.js';\nimport { registerStyles, ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst MIN_ALLOWED_TIME = '00:00:00.000';\nconst MAX_ALLOWED_TIME = '23:59:59.999';\n\nregisterStyles('vaadin-time-picker', inputFieldShared, { moduleId: 'vaadin-time-picker-styles' });\n\n/**\n * `<vaadin-time-picker>` is a Web Component providing a time-selection field.\n *\n * ```html\n * <vaadin-time-picker></vaadin-time-picker>\n * ```\n * ```js\n * timePicker.value = '14:30';\n * ```\n *\n * When the selected `value` is changed, a `value-changed` event is triggered.\n *\n * ### Styling\n *\n * The following custom properties are available for styling:\n *\n * Custom property                         | Description                | Default\n * ----------------------------------------|----------------------------|---------\n * `--vaadin-field-default-width`          | Default width of the field | `12em`\n * `--vaadin-combo-box-overlay-max-height` | Max height of the overlay  | `65vh`\n *\n * `<vaadin-time-picker>` provides the same set of shadow DOM parts and state attributes as `<vaadin-text-field>`.\n * See [`<vaadin-text-field>`](#/elements/vaadin-text-field) for the styling documentation.\n *\n * In addition to `<vaadin-text-field>` parts, the following parts are available for theming:\n *\n * Part name       | Description\n * ----------------|----------------\n * `toggle-button` | The toggle button\n *\n * In addition to `<vaadin-text-field>` state attributes, the following state attributes are available for theming:\n *\n * Attribute | Description\n * ----------|------------------------------------------\n * `opened`  | Set when the time-picker dropdown is open\n *\n * ### Internal components\n *\n * In addition to `<vaadin-time-picker>` itself, the following internal\n * components are themable:\n *\n * - `<vaadin-time-picker-combo-box>` - has the same API as [`<vaadin-combo-box-light>`](#/elements/vaadin-combo-box-light).\n * - `<vaadin-time-picker-overlay>` - has the same API as [`<vaadin-overlay>`](#/elements/vaadin-overlay).\n * - `<vaadin-time-picker-item>` - has the same API as [`<vaadin-item>`](#/elements/vaadin-item).\n * - [`<vaadin-input-container>`](#/elements/vaadin-input-container) - an internal element wrapping the input.\n *\n * Note: the `theme` attribute value set on `<vaadin-time-picker>` is\n * propagated to the internal components listed above.\n *\n * See [Styling Components](https://vaadin.com/docs/latest/styling/styling-components) documentation.\n *\n * @fires {Event} change - Fired when the user commits a value change.\n * @fires {CustomEvent} invalid-changed - Fired when the `invalid` property changes.\n * @fires {CustomEvent} opened-changed - Fired when the `opened` property changes.\n * @fires {CustomEvent} value-changed - Fired when the `value` property changes.\n * @fires {CustomEvent} validated - Fired whenever the field is validated.\n *\n * @extends HTMLElement\n * @mixes ElementMixin\n * @mixes ThemableMixin\n * @mixes InputControlMixin\n * @mixes PatternMixin\n */\nclass TimePicker extends PatternMixin(InputControlMixin(ThemableMixin(ElementMixin(PolymerElement)))) {\n  static get is() {\n    return 'vaadin-time-picker';\n  }\n\n  static get template() {\n    return html`\n      <style>\n        /* See https://github.com/vaadin/vaadin-time-picker/issues/145 */\n        :host([dir='rtl']) [part='input-field'] {\n          direction: ltr;\n        }\n\n        :host([dir='rtl']) [part='input-field'] ::slotted(input)::placeholder {\n          direction: rtl;\n          text-align: left;\n        }\n\n        [part~='toggle-button'] {\n          cursor: pointer;\n        }\n      </style>\n\n      <div class=\"vaadin-time-picker-container\">\n        <div part=\"label\">\n          <slot name=\"label\"></slot>\n          <span part=\"required-indicator\" aria-hidden=\"true\" on-click=\"focus\"></span>\n        </div>\n\n        <vaadin-time-picker-combo-box\n          id=\"comboBox\"\n          filtered-items=\"[[__dropdownItems]]\"\n          value=\"{{_comboBoxValue}}\"\n          opened=\"{{opened}}\"\n          disabled=\"[[disabled]]\"\n          readonly=\"[[readonly]]\"\n          clear-button-visible=\"[[clearButtonVisible]]\"\n          auto-open-disabled=\"[[autoOpenDisabled]]\"\n          overlay-class=\"[[overlayClass]]\"\n          position-target=\"[[_inputContainer]]\"\n          theme$=\"[[_theme]]\"\n          on-change=\"__onComboBoxChange\"\n          on-has-input-value-changed=\"__onComboBoxHasInputValueChanged\"\n        >\n          <vaadin-input-container\n            part=\"input-field\"\n            readonly=\"[[readonly]]\"\n            disabled=\"[[disabled]]\"\n            invalid=\"[[invalid]]\"\n            theme$=\"[[_theme]]\"\n          >\n            <slot name=\"prefix\" slot=\"prefix\"></slot>\n            <slot name=\"input\"></slot>\n            <div id=\"clearButton\" part=\"clear-button\" slot=\"suffix\" aria-hidden=\"true\"></div>\n            <div id=\"toggleButton\" class=\"toggle-button\" part=\"toggle-button\" slot=\"suffix\" aria-hidden=\"true\"></div>\n          </vaadin-input-container>\n        </vaadin-time-picker-combo-box>\n\n        <div part=\"helper-text\">\n          <slot name=\"helper\"></slot>\n        </div>\n\n        <div part=\"error-message\">\n          <slot name=\"error-message\"></slot>\n        </div>\n      </div>\n      <slot name=\"tooltip\"></slot>\n    `;\n  }\n\n  static get properties() {\n    return {\n      /**\n       * The time value for this element.\n       *\n       * Supported time formats are in ISO 8601:\n       * - `hh:mm` (default)\n       * - `hh:mm:ss`\n       * - `hh:mm:ss.fff`\n       * @type {string}\n       */\n      value: {\n        type: String,\n        notify: true,\n        value: '',\n      },\n\n      /**\n       * True if the dropdown is open, false otherwise.\n       */\n      opened: {\n        type: Boolean,\n        notify: true,\n        value: false,\n        reflectToAttribute: true,\n      },\n\n      /**\n       * Minimum time allowed.\n       *\n       * Supported time formats are in ISO 8601:\n       * - `hh:mm`\n       * - `hh:mm:ss`\n       * - `hh:mm:ss.fff`\n       * @type {string}\n       */\n      min: {\n        type: String,\n        value: '',\n      },\n\n      /**\n       * Maximum time allowed.\n       *\n       * Supported time formats are in ISO 8601:\n       * - `hh:mm`\n       * - `hh:mm:ss`\n       * - `hh:mm:ss.fff`\n       * @type {string}\n       */\n      max: {\n        type: String,\n        value: '',\n      },\n\n      /**\n       * Defines the time interval (in seconds) between the items displayed\n       * in the time selection box. The default is 1 hour (i.e. `3600`).\n       *\n       * It also configures the precision of the value string. By default\n       * the component formats values as `hh:mm` but setting a step value\n       * lower than one minute or one second, format resolution changes to\n       * `hh:mm:ss` and `hh:mm:ss.fff` respectively.\n       *\n       * Unit must be set in seconds, and for correctly configuring intervals\n       * in the dropdown, it need to evenly divide a day.\n       *\n       * Note: it is possible to define step that is dividing an hour in inexact\n       * fragments (i.e. 5760 seconds which equals 1 hour 36 minutes), but it is\n       * not recommended to use it for better UX experience.\n       */\n      step: {\n        type: Number,\n      },\n\n      /**\n       * Set true to prevent the overlay from opening automatically.\n       * @attr {boolean} auto-open-disabled\n       */\n      autoOpenDisabled: Boolean,\n\n      /**\n       * A space-delimited list of CSS class names to set on the overlay element.\n       *\n       * @attr {string} overlay-class\n       */\n      overlayClass: {\n        type: String,\n      },\n\n      /** @private */\n      __dropdownItems: {\n        type: Array,\n      },\n\n      /**\n       * The object used to localize this component.\n       * To change the default localization, replace the entire\n       * _i18n_ object or just the property you want to modify.\n       *\n       * The object has the following JSON structure:\n       *\n       * ```\n       * {\n       *   // A function to format given `Object` as\n       *   // time string. Object is in the format `{ hours: ..., minutes: ..., seconds: ..., milliseconds: ... }`\n       *   formatTime: (time) => {\n       *     // returns a string representation of the given\n       *     // object in `hh` / 'hh:mm' / 'hh:mm:ss' / 'hh:mm:ss.fff' - formats\n       *   },\n       *\n       *   // A function to parse the given text to an `Object` in the format\n       *   // `{ hours: ..., minutes: ..., seconds: ..., milliseconds: ... }`.\n       *   // Must properly parse (at least) text\n       *   // formatted by `formatTime`.\n       *   parseTime: text => {\n       *     // Parses a string in object/string that can be formatted by`formatTime`.\n       *   }\n       * }\n       * ```\n       *\n       * Both `formatTime` and `parseTime` need to be implemented\n       * to ensure the component works properly.\n       *\n       * @type {!TimePickerI18n}\n       */\n      i18n: {\n        type: Object,\n        value: () => {\n          return {\n            formatTime: (time) => {\n              if (!time) {\n                return;\n              }\n\n              const pad = (num = 0, fmt = '00') => (fmt + num).substr((fmt + num).length - fmt.length);\n              // Always display hour and minute\n              let timeString = `${pad(time.hours)}:${pad(time.minutes)}`;\n              // Adding second and millisecond depends on resolution\n              if (time.seconds !== undefined) {\n                timeString += `:${pad(time.seconds)}`;\n              }\n              if (time.milliseconds !== undefined) {\n                timeString += `.${pad(time.milliseconds, '000')}`;\n              }\n              return timeString;\n            },\n            parseTime: (text) => {\n              // Parsing with RegExp to ensure correct format\n              const MATCH_HOURS = '(\\\\d|[0-1]\\\\d|2[0-3])';\n              const MATCH_MINUTES = '(\\\\d|[0-5]\\\\d)';\n              const MATCH_SECONDS = MATCH_MINUTES;\n              const MATCH_MILLISECONDS = '(\\\\d{1,3})';\n              const re = new RegExp(\n                `^${MATCH_HOURS}(?::${MATCH_MINUTES}(?::${MATCH_SECONDS}(?:\\\\.${MATCH_MILLISECONDS})?)?)?$`,\n                'u',\n              );\n              const parts = re.exec(text);\n              if (parts) {\n                // Allows setting the milliseconds with hundreds and tens precision\n                if (parts[4]) {\n                  while (parts[4].length < 3) {\n                    parts[4] += '0';\n                  }\n                }\n                return { hours: parts[1], minutes: parts[2], seconds: parts[3], milliseconds: parts[4] };\n              }\n            },\n          };\n        },\n      },\n\n      /** @private */\n      _comboBoxValue: {\n        type: String,\n        observer: '__comboBoxValueChanged',\n      },\n\n      /** @private */\n      _inputContainer: Object,\n    };\n  }\n\n  static get observers() {\n    return ['__updateDropdownItems(i18n.*, min, max, step)'];\n  }\n\n  static get constraints() {\n    return [...super.constraints, 'min', 'max'];\n  }\n\n  /**\n   * Used by `InputControlMixin` as a reference to the clear button element.\n   * @protected\n   * @return {!HTMLElement}\n   */\n  get clearElement() {\n    return this.$.clearButton;\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n\n    this.addController(\n      new InputController(this, (input) => {\n        this._setInputElement(input);\n        this._setFocusElement(input);\n        this.stateTarget = input;\n        this.ariaTarget = input;\n      }),\n    );\n    this.addController(new LabelledInputController(this.inputElement, this._labelController));\n    this._inputContainer = this.shadowRoot.querySelector('[part~=\"input-field\"]');\n\n    this._tooltipController = new TooltipController(this);\n    this._tooltipController.setShouldShow((timePicker) => !timePicker.opened);\n    this._tooltipController.setPosition('top');\n    this.addController(this._tooltipController);\n  }\n\n  /**\n   * Override method inherited from `InputMixin` to forward the input to combo-box.\n   * @protected\n   * @override\n   */\n  _inputElementChanged(input) {\n    super._inputElementChanged(input);\n\n    if (input) {\n      this.$.comboBox._setInputElement(input);\n    }\n  }\n\n  /**\n   * Opens the dropdown list.\n   */\n  open() {\n    if (!this.disabled && !this.readonly) {\n      this.opened = true;\n    }\n  }\n\n  /**\n   * Closes the dropdown list.\n   */\n  close() {\n    this.opened = false;\n  }\n\n  /**\n   * Returns true if the current input value satisfies all constraints (if any).\n   * You can override this method for custom validations.\n   *\n   * @return {boolean} True if the value is valid\n   */\n  checkValidity() {\n    return !!(\n      this.inputElement.checkValidity() &&\n      (!this.value || this._timeAllowed(this.i18n.parseTime(this.value))) &&\n      (!this._comboBoxValue || this.i18n.parseTime(this._comboBoxValue))\n    );\n  }\n\n  /**\n   * Override method inherited from `FocusMixin` to validate on blur.\n   * @param {boolean} focused\n   * @protected\n   */\n  _setFocused(focused) {\n    super._setFocused(focused);\n\n    if (!focused) {\n      this.validate();\n    }\n  }\n\n  /** @private */\n  __validDayDivisor(step) {\n    // Valid if undefined, or exact divides a day, or has millisecond resolution\n    return !step || (24 * 3600) % step === 0 || (step < 1 && ((step % 1) * 1000) % 1 === 0);\n  }\n\n  /**\n   * Override an event listener from `KeyboardMixin`.\n   * @param {!KeyboardEvent} e\n   * @protected\n   */\n  _onKeyDown(e) {\n    super._onKeyDown(e);\n\n    if (this.readonly || this.disabled || this.__dropdownItems.length) {\n      return;\n    }\n\n    const stepResolution = (this.__validDayDivisor(this.step) && this.step) || 60;\n\n    if (e.keyCode === 40) {\n      this.__onArrowPressWithStep(-stepResolution);\n    } else if (e.keyCode === 38) {\n      this.__onArrowPressWithStep(stepResolution);\n    }\n  }\n\n  /**\n   * Override an event listener from `KeyboardMixin`.\n   * Do not call `super` in order to override clear\n   * button logic defined in `InputControlMixin`.\n   * @param {Event} event\n   * @protected\n   */\n  _onEscape() {\n    // Do nothing, the internal combo-box handles Escape.\n  }\n\n  /** @private */\n  __onArrowPressWithStep(step) {\n    const objWithStep = this.__addStep(this.__getMsec(this.__memoValue), step, true);\n    this.__memoValue = objWithStep;\n    this.inputElement.value = this.i18n.formatTime(this.__validateTime(objWithStep));\n    this.__dispatchChange();\n  }\n\n  /** @private */\n  __dispatchChange() {\n    this.dispatchEvent(new CustomEvent('change', { bubbles: true }));\n  }\n\n  /**\n   * Returning milliseconds from Object in the format `{ hours: ..., minutes: ..., seconds: ..., milliseconds: ... }`\n   * @private\n   */\n  __getMsec(obj) {\n    let result = ((obj && obj.hours) || 0) * 60 * 60 * 1000;\n    result += ((obj && obj.minutes) || 0) * 60 * 1000;\n    result += ((obj && obj.seconds) || 0) * 1000;\n    result += (obj && parseInt(obj.milliseconds)) || 0;\n\n    return result;\n  }\n\n  /**\n   * Returning seconds from Object in the format `{ hours: ..., minutes: ..., seconds: ..., milliseconds: ... }`\n   * @private\n   */\n  __getSec(obj) {\n    let result = ((obj && obj.hours) || 0) * 60 * 60;\n    result += ((obj && obj.minutes) || 0) * 60;\n    result += (obj && obj.seconds) || 0;\n    result += (obj && obj.milliseconds / 1000) || 0;\n\n    return result;\n  }\n\n  /**\n   * Returning Object in the format `{ hours: ..., minutes: ..., seconds: ..., milliseconds: ... }`\n   * from the result of adding step value in milliseconds to the milliseconds amount.\n   * With `precision` parameter rounding the value to the closest step valid interval.\n   * @private\n   */\n  __addStep(msec, step, precision) {\n    // If the time is `00:00` and step changes value downwards, it should be considered as `24:00`\n    if (msec === 0 && step < 0) {\n      msec = 24 * 60 * 60 * 1000;\n    }\n\n    const stepMsec = step * 1000;\n    const diffToNext = msec % stepMsec;\n    if (stepMsec < 0 && diffToNext && precision) {\n      msec -= diffToNext;\n    } else if (stepMsec > 0 && diffToNext && precision) {\n      msec -= diffToNext - stepMsec;\n    } else {\n      msec += stepMsec;\n    }\n\n    const hh = Math.floor(msec / 1000 / 60 / 60);\n    msec -= hh * 1000 * 60 * 60;\n    const mm = Math.floor(msec / 1000 / 60);\n    msec -= mm * 1000 * 60;\n    const ss = Math.floor(msec / 1000);\n    msec -= ss * 1000;\n\n    return { hours: hh < 24 ? hh : 0, minutes: mm, seconds: ss, milliseconds: msec };\n  }\n\n  /** @private */\n  __updateDropdownItems(i8n, min, max, step) {\n    const minTimeObj = this.__validateTime(this.__parseISO(min || MIN_ALLOWED_TIME));\n    const minSec = this.__getSec(minTimeObj);\n\n    const maxTimeObj = this.__validateTime(this.__parseISO(max || MAX_ALLOWED_TIME));\n    const maxSec = this.__getSec(maxTimeObj);\n\n    this.__dropdownItems = this.__generateDropdownList(minSec, maxSec, step);\n\n    if (step !== this.__oldStep) {\n      this.__oldStep = step;\n      const parsedObj = this.__validateTime(this.__parseISO(this.value));\n      this.__updateValue(parsedObj);\n    }\n\n    if (this.value) {\n      this._comboBoxValue = this.i18n.formatTime(this.i18n.parseTime(this.value));\n    }\n  }\n\n  /** @private */\n  __generateDropdownList(minSec, maxSec, step) {\n    if (step < 15 * 60 || !this.__validDayDivisor(step)) {\n      return [];\n    }\n\n    const generatedList = [];\n\n    // Default step in overlay items is 1 hour\n    if (!step) {\n      step = 3600;\n    }\n\n    let time = -step + minSec;\n    while (time + step >= minSec && time + step <= maxSec) {\n      const timeObj = this.__validateTime(this.__addStep(time * 1000, step));\n      time += step;\n      const formatted = this.i18n.formatTime(timeObj);\n      generatedList.push({ label: formatted, value: formatted });\n    }\n\n    return generatedList;\n  }\n\n  /**\n   * Override an observer from `InputMixin`.\n   * @protected\n   * @override\n   */\n  _valueChanged(value, oldValue) {\n    const parsedObj = (this.__memoValue = this.__parseISO(value));\n    const newValue = this.__formatISO(parsedObj) || '';\n\n    if (value !== '' && value !== null && !parsedObj) {\n      // Value can not be parsed, reset to the old one.\n      this.value = oldValue === undefined ? '' : oldValue;\n    } else if (value !== newValue) {\n      // Value can be parsed (e.g. 12 -> 12:00), adjust.\n      this.value = newValue;\n    } else if (this.__keepInvalidInput) {\n      // User input could not be parsed and was reset\n      // to empty string, do not update input value.\n      delete this.__keepInvalidInput;\n    } else {\n      this.__updateInputValue(parsedObj);\n    }\n\n    this._toggleHasValue(this._hasValue);\n  }\n\n  /** @private */\n  __comboBoxValueChanged(value, oldValue) {\n    if (value === '' && oldValue === undefined) {\n      return;\n    }\n\n    const parsedObj = this.i18n.parseTime(value);\n    const newValue = this.i18n.formatTime(parsedObj) || '';\n\n    if (parsedObj) {\n      if (value !== newValue) {\n        this._comboBoxValue = newValue;\n      } else {\n        this.__updateValue(parsedObj);\n      }\n    } else {\n      // If the user input can not be parsed, set a flag\n      // that prevents `__valueChanged` from removing the input\n      // after setting the value property to an empty string below.\n      if (this.value !== '' && value !== '') {\n        this.__keepInvalidInput = true;\n      }\n\n      this.value = '';\n    }\n  }\n\n  /** @private */\n  __onComboBoxChange(event) {\n    event.stopPropagation();\n\n    this.validate();\n\n    this.__dispatchChange();\n  }\n\n  /**\n   * Synchronizes the `_hasInputValue` property with the internal combo-box's one.\n   *\n   * @private\n   */\n  __onComboBoxHasInputValueChanged() {\n    this._hasInputValue = this.$.comboBox._hasInputValue;\n  }\n\n  /** @private */\n  __updateValue(obj) {\n    const timeString = this.__formatISO(this.__validateTime(obj)) || '';\n    this.value = timeString;\n  }\n\n  /** @private */\n  __updateInputValue(obj) {\n    const timeString = this.i18n.formatTime(this.__validateTime(obj)) || '';\n    this._comboBoxValue = timeString;\n  }\n\n  /** @private */\n  __validateTime(timeObject) {\n    if (timeObject) {\n      const stepSegment = this.__getStepSegment();\n      timeObject.hours = parseInt(timeObject.hours);\n      timeObject.minutes = parseInt(timeObject.minutes || 0);\n      timeObject.seconds = stepSegment < 3 ? undefined : parseInt(timeObject.seconds || 0);\n      timeObject.milliseconds = stepSegment < 4 ? undefined : parseInt(timeObject.milliseconds || 0);\n    }\n    return timeObject;\n  }\n\n  /** @private */\n  __getStepSegment() {\n    if (this.step % 3600 === 0) {\n      // Accept hours\n      return 1;\n    } else if (this.step % 60 === 0 || !this.step) {\n      // Accept minutes\n      return 2;\n    } else if (this.step % 1 === 0) {\n      // Accept seconds\n      return 3;\n    } else if (this.step < 1) {\n      // Accept milliseconds\n      return 4;\n    }\n    return undefined;\n  }\n\n  /** @private */\n  __formatISO(time) {\n    // The default i18n formatter implementation is ISO 8601 compliant\n    return TimePicker.properties.i18n.value().formatTime(time);\n  }\n\n  /** @private */\n  __parseISO(text) {\n    // The default i18n parser implementation is ISO 8601 compliant\n    return TimePicker.properties.i18n.value().parseTime(text);\n  }\n\n  /**\n   * Returns true if `time` satisfies the `min` and `max` constraints (if any).\n   *\n   * @param {!TimePickerTime} time Value to check against constraints\n   * @return {boolean} True if `time` satisfies the constraints\n   * @protected\n   */\n  _timeAllowed(time) {\n    const parsedMin = this.i18n.parseTime(this.min || MIN_ALLOWED_TIME);\n    const parsedMax = this.i18n.parseTime(this.max || MAX_ALLOWED_TIME);\n\n    return (\n      (!this.__getMsec(parsedMin) || this.__getMsec(time) >= this.__getMsec(parsedMin)) &&\n      (!this.__getMsec(parsedMax) || this.__getMsec(time) <= this.__getMsec(parsedMax))\n    );\n  }\n\n  /**\n   * Override method inherited from `InputControlMixin`.\n   * @protected\n   */\n  _onClearButtonClick() {}\n\n  /**\n   * Override method inherited from `InputConstraintsMixin`.\n   * @protected\n   */\n  _onChange() {}\n\n  /**\n   * Override method inherited from `InputMixin`.\n   * @protected\n   */\n  _onInput() {}\n\n  /**\n   * Fired when the user commits a value change.\n   *\n   * @event change\n   */\n}\n\ncustomElements.define(TimePicker.is, TimePicker);\n\nexport { TimePicker };\n","/**\n * @license\n * Copyright (c) 2022 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { Overlay } from '@vaadin/overlay/src/vaadin-overlay.js';\nimport { PositionMixin } from '@vaadin/overlay/src/vaadin-overlay-position-mixin.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles(\n  'vaadin-tooltip-overlay',\n  css`\n    :host {\n      z-index: 1100;\n    }\n\n    [part='overlay'] {\n      max-width: 40ch;\n    }\n\n    :host([position^='top'][top-aligned]) [part='overlay'],\n    :host([position^='bottom'][top-aligned]) [part='overlay'] {\n      margin-top: var(--vaadin-tooltip-offset-top, 0);\n    }\n\n    :host([position^='top'][bottom-aligned]) [part='overlay'],\n    :host([position^='bottom'][bottom-aligned]) [part='overlay'] {\n      margin-bottom: var(--vaadin-tooltip-offset-bottom, 0);\n    }\n\n    :host([position^='start'][start-aligned]) [part='overlay'],\n    :host([position^='end'][start-aligned]) [part='overlay'] {\n      margin-inline-start: var(--vaadin-tooltip-offset-start, 0);\n    }\n\n    :host([position^='start'][end-aligned]) [part='overlay'],\n    :host([position^='end'][end-aligned]) [part='overlay'] {\n      margin-inline-end: var(--vaadin-tooltip-offset-end, 0);\n    }\n\n    @media (forced-colors: active) {\n      [part='overlay'] {\n        outline: 1px dashed;\n      }\n    }\n  `,\n  { moduleId: 'vaadin-tooltip-overlay-styles' },\n);\n\nlet memoizedTemplate;\n\n/**\n * An element used internally by `<vaadin-tooltip>`. Not intended to be used separately.\n *\n * @extends Overlay\n * @private\n */\nclass TooltipOverlay extends PositionMixin(Overlay) {\n  static get is() {\n    return 'vaadin-tooltip-overlay';\n  }\n\n  static get template() {\n    if (!memoizedTemplate) {\n      memoizedTemplate = super.template.cloneNode(true);\n      memoizedTemplate.content.querySelector('[part~=\"overlay\"]').removeAttribute('tabindex');\n\n      // Remove whitespace text nodes around the content slot to allow \"white-space: pre\"\n      memoizedTemplate.content.querySelector('[part~=\"content\"]').innerHTML = '<slot></slot>';\n    }\n\n    return memoizedTemplate;\n  }\n\n  static get properties() {\n    return {\n      position: {\n        type: String,\n        reflectToAttribute: true,\n      },\n    };\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n\n    // When setting `manual` and `opened` attributes, the overlay is already moved to body\n    // by the time when `ready()` callback of the `vaadin-tooltip` is executed by Polymer,\n    // so querySelector() would return null. So we use this workaround to set properties.\n    this.owner = this.__dataHost;\n    this.owner._overlayElement = this;\n  }\n\n  requestContentUpdate() {\n    super.requestContentUpdate();\n\n    this.toggleAttribute('hidden', this.textContent.trim() === '');\n\n    // Copy custom properties from the tooltip\n    if (this.positionTarget && this.owner) {\n      const style = getComputedStyle(this.owner);\n      ['top', 'bottom', 'start', 'end'].forEach((prop) => {\n        this.style.setProperty(\n          `--vaadin-tooltip-offset-${prop}`,\n          style.getPropertyValue(`--vaadin-tooltip-offset-${prop}`),\n        );\n      });\n    }\n  }\n\n  /**\n   * @protected\n   * @override\n   */\n  _updatePosition() {\n    super._updatePosition();\n\n    if (!this.positionTarget) {\n      return;\n    }\n\n    // Center the tooltip overlay horizontally\n    if (this.position === 'bottom' || this.position === 'top') {\n      const targetRect = this.positionTarget.getBoundingClientRect();\n      const overlayRect = this.$.overlay.getBoundingClientRect();\n\n      const offset = targetRect.width / 2 - overlayRect.width / 2;\n\n      if (this.style.left) {\n        const left = overlayRect.left + offset;\n        if (left > 0) {\n          this.style.left = `${left}px`;\n        }\n      }\n\n      if (this.style.right) {\n        const right = parseFloat(this.style.right) + offset;\n        if (right > 0) {\n          this.style.right = `${right}px`;\n        }\n      }\n    }\n\n    // Center the tooltip overlay vertically\n    if (this.position === 'start' || this.position === 'end') {\n      const targetRect = this.positionTarget.getBoundingClientRect();\n      const overlayRect = this.$.overlay.getBoundingClientRect();\n\n      const offset = targetRect.height / 2 - overlayRect.height / 2;\n      this.style.top = `${overlayRect.top + offset}px`;\n    }\n  }\n}\n\ncustomElements.define(TooltipOverlay.is, TooltipOverlay);\n","import '@vaadin/vaadin-lumo-styles/color.js';\nimport '@vaadin/vaadin-lumo-styles/style.js';\nimport '@vaadin/vaadin-lumo-styles/typography.js';\nimport { overlay } from '@vaadin/vaadin-lumo-styles/mixins/overlay.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nconst tooltipOverlay = css`\n  :host {\n    --vaadin-tooltip-offset-top: var(--lumo-space-xs);\n    --vaadin-tooltip-offset-bottom: var(--lumo-space-xs);\n    --vaadin-tooltip-offset-start: var(--lumo-space-xs);\n    --vaadin-tooltip-offset-end: var(--lumo-space-xs);\n  }\n\n  [part='overlay'] {\n    background: var(--lumo-base-color) linear-gradient(var(--lumo-contrast-5pct), var(--lumo-contrast-5pct));\n    color: var(--lumo-body-text-color);\n    font-size: var(--lumo-font-size-xs);\n    line-height: var(--lumo-line-height-s);\n  }\n\n  [part='content'] {\n    padding: var(--lumo-space-xs) var(--lumo-space-s);\n  }\n`;\n\nregisterStyles('vaadin-tooltip-overlay', [overlay, tooltipOverlay], { moduleId: 'lumo-tooltip-overlay' });\n","/**\n * @license\n * Copyright (c) 2022 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport './vaadin-tooltip-overlay.js';\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { isKeyboardActive } from '@vaadin/a11y-base/src/focus-utils.js';\nimport { microTask } from '@vaadin/component-base/src/async.js';\nimport { Debouncer } from '@vaadin/component-base/src/debounce.js';\nimport { addValueToAttribute, removeValueFromAttribute } from '@vaadin/component-base/src/dom-utils.js';\nimport { ElementMixin } from '@vaadin/component-base/src/element-mixin.js';\nimport { OverlayClassMixin } from '@vaadin/component-base/src/overlay-class-mixin.js';\nimport { generateUniqueId } from '@vaadin/component-base/src/unique-id-utils.js';\nimport { ThemePropertyMixin } from '@vaadin/vaadin-themable-mixin/vaadin-theme-property-mixin.js';\n\nconst DEFAULT_DELAY = 500;\n\nlet defaultFocusDelay = DEFAULT_DELAY;\nlet defaultHoverDelay = DEFAULT_DELAY;\nlet defaultHideDelay = DEFAULT_DELAY;\n\nconst closing = new Set();\n\nlet warmedUp = false;\nlet warmUpTimeout = null;\nlet cooldownTimeout = null;\n\n/**\n * Resets the global tooltip warmup and cooldown state.\n * Only for internal use in tests.\n * @private\n */\nexport function resetGlobalTooltipState() {\n  warmedUp = false;\n  clearTimeout(warmUpTimeout);\n  clearTimeout(cooldownTimeout);\n  closing.clear();\n}\n\n/**\n * Controller for handling tooltip opened state.\n */\nclass TooltipStateController {\n  constructor(host) {\n    this.host = host;\n  }\n\n  /** @private */\n  get openedProp() {\n    return this.host.manual ? 'opened' : '_autoOpened';\n  }\n\n  /** @private */\n  get focusDelay() {\n    const tooltip = this.host;\n    return tooltip.focusDelay != null && tooltip.focusDelay > 0 ? tooltip.focusDelay : defaultFocusDelay;\n  }\n\n  /** @private */\n  get hoverDelay() {\n    const tooltip = this.host;\n    return tooltip.hoverDelay != null && tooltip.hoverDelay > 0 ? tooltip.hoverDelay : defaultHoverDelay;\n  }\n\n  /** @private */\n  get hideDelay() {\n    const tooltip = this.host;\n    return tooltip.hideDelay != null && tooltip.hideDelay > 0 ? tooltip.hideDelay : defaultHideDelay;\n  }\n\n  /**\n   * Schedule opening the tooltip.\n   * @param {Object} options\n   */\n  open(options = { immediate: false }) {\n    const { immediate, hover, focus } = options;\n    const isHover = hover && this.hoverDelay > 0;\n    const isFocus = focus && this.focusDelay > 0;\n\n    if (!immediate && (isHover || isFocus) && !this.__closeTimeout) {\n      this.__warmupTooltip(isFocus);\n    } else {\n      this.__showTooltip();\n    }\n  }\n\n  /**\n   * Schedule closing the tooltip.\n   * @param {boolean} immediate\n   */\n  close(immediate) {\n    if (!immediate && this.hideDelay > 0) {\n      this.__scheduleClose();\n    } else {\n      this.__abortClose();\n      this._setOpened(false);\n    }\n\n    this.__abortWarmUp();\n\n    if (warmedUp) {\n      // Re-start cooldown timer on each tooltip closing.\n      this.__abortCooldown();\n      this.__scheduleCooldown();\n    }\n  }\n\n  /** @private */\n  _isOpened() {\n    return this.host[this.openedProp];\n  }\n\n  /** @private */\n  _setOpened(opened) {\n    this.host[this.openedProp] = opened;\n  }\n\n  /** @private */\n  __flushClosingTooltips() {\n    closing.forEach((tooltip) => {\n      tooltip._stateController.close(true);\n      closing.delete(tooltip);\n    });\n  }\n\n  /** @private */\n  __showTooltip() {\n    this.__abortClose();\n    this.__flushClosingTooltips();\n\n    this._setOpened(true);\n    warmedUp = true;\n\n    // Abort previously scheduled timers.\n    this.__abortWarmUp();\n    this.__abortCooldown();\n  }\n\n  /** @private */\n  __warmupTooltip(isFocus) {\n    if (!this._isOpened()) {\n      // First tooltip is opened, warm up.\n      if (!warmedUp) {\n        this.__scheduleWarmUp(isFocus);\n      } else {\n        // Warmed up, show another tooltip.\n        this.__showTooltip();\n      }\n    }\n  }\n\n  /** @private */\n  __abortClose() {\n    if (this.__closeTimeout) {\n      clearTimeout(this.__closeTimeout);\n      this.__closeTimeout = null;\n    }\n  }\n\n  /** @private */\n  __abortCooldown() {\n    if (cooldownTimeout) {\n      clearTimeout(cooldownTimeout);\n      cooldownTimeout = null;\n    }\n  }\n\n  /** @private */\n  __abortWarmUp() {\n    if (warmUpTimeout) {\n      clearTimeout(warmUpTimeout);\n      warmUpTimeout = null;\n    }\n  }\n\n  /** @private */\n  __scheduleClose() {\n    if (this._isOpened()) {\n      closing.add(this.host);\n\n      this.__closeTimeout = setTimeout(() => {\n        closing.delete(this.host);\n        this.__closeTimeout = null;\n        this._setOpened(false);\n      }, this.hideDelay);\n    }\n  }\n\n  /** @private */\n  __scheduleCooldown() {\n    cooldownTimeout = setTimeout(() => {\n      cooldownTimeout = null;\n      warmedUp = false;\n    }, this.hideDelay);\n  }\n\n  /** @private */\n  __scheduleWarmUp(isFocus) {\n    const delay = isFocus ? this.focusDelay : this.hoverDelay;\n    warmUpTimeout = setTimeout(() => {\n      warmUpTimeout = null;\n      warmedUp = true;\n      this.__showTooltip();\n    }, delay);\n  }\n}\n\n/**\n * `<vaadin-tooltip>` is a Web Component for creating tooltips.\n *\n * ```html\n * <button id=\"confirm\">Confirm</button>\n * <vaadin-tooltip text=\"Click to save changes\" for=\"confirm\"></vaadin-tooltip>\n * ```\n *\n * ### Styling\n *\n * `<vaadin-tooltip>` uses `<vaadin-tooltip-overlay>` internal\n * themable component as the actual visible overlay.\n *\n * See [`<vaadin-overlay>`](#/elements/vaadin-overlay) documentation\n * for `<vaadin-tooltip-overlay>` parts.\n *\n * The following state attributes are available for styling:\n *\n * Attribute        | Description\n * -----------------|----------------------------------------\n * `position`       | Reflects the `position` property value.\n *\n * Note: the `theme` attribute value set on `<vaadin-tooltip>` is\n * propagated to the internal `<vaadin-tooltip-overlay>` component.\n *\n * ### Custom CSS Properties\n *\n * The following custom CSS properties are available on the `<vaadin-tooltip>` element:\n *\n * Custom CSS property              | Description\n * ---------------------------------|-------------\n * `--vaadin-tooltip-offset-top`    | Used as an offset when the tooltip is aligned vertically below the target\n * `--vaadin-tooltip-offset-bottom` | Used as an offset when the tooltip is aligned vertically above the target\n * `--vaadin-tooltip-offset-start`  | Used as an offset when the tooltip is aligned horizontally after the target\n * `--vaadin-tooltip-offset-end`    | Used as an offset when the tooltip is aligned horizontally before the target\n *\n * See [Styling Components](https://vaadin.com/docs/latest/styling/styling-components) documentation.\n *\n * @extends HTMLElement\n * @mixes ElementMixin\n * @mixes OverlayClassMixin\n * @mixes ThemePropertyMixin\n */\nclass Tooltip extends OverlayClassMixin(ThemePropertyMixin(ElementMixin(PolymerElement))) {\n  static get is() {\n    return 'vaadin-tooltip';\n  }\n\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: none;\n        }\n      </style>\n      <vaadin-tooltip-overlay\n        id=\"[[_uniqueId]]\"\n        role=\"tooltip\"\n        renderer=\"[[_renderer]]\"\n        theme$=\"[[_theme]]\"\n        opened=\"[[__computeOpened(manual, opened, _autoOpened, _isConnected)]]\"\n        position-target=\"[[target]]\"\n        position=\"[[__effectivePosition]]\"\n        no-horizontal-overlap$=\"[[__computeNoHorizontalOverlap(__effectivePosition)]]\"\n        no-vertical-overlap$=\"[[__computeNoVerticalOverlap(__effectivePosition)]]\"\n        horizontal-align=\"[[__computeHorizontalAlign(__effectivePosition)]]\"\n        vertical-align=\"[[__computeVerticalAlign(__effectivePosition)]]\"\n        on-mouseleave=\"__onOverlayMouseLeave\"\n        modeless\n      ></vaadin-tooltip-overlay>\n    `;\n  }\n\n  static get properties() {\n    return {\n      /**\n       * Object with properties passed to `generator` and\n       * `shouldShow` functions for generating tooltip text\n       * or detecting whether to show the tooltip or not.\n       */\n      context: {\n        type: Object,\n        value: () => {\n          return {};\n        },\n      },\n\n      /**\n       * The delay in milliseconds before the tooltip\n       * is opened on keyboard focus, when not in manual mode.\n       * @attr {number} focus-delay\n       */\n      focusDelay: {\n        type: Number,\n      },\n\n      /**\n       * The id of the element used as a tooltip trigger.\n       * The element should be in the DOM by the time when\n       * the attribute is set, otherwise a warning is shown.\n       */\n      for: {\n        type: String,\n        observer: '__forChanged',\n      },\n\n      /**\n       * The delay in milliseconds before the tooltip\n       * is closed on losing hover, when not in manual mode.\n       * On blur, the tooltip is closed immediately.\n       * @attr {number} hide-delay\n       */\n      hideDelay: {\n        type: Number,\n      },\n\n      /**\n       * The delay in milliseconds before the tooltip\n       * is opened on hover, when not in manual mode.\n       * @attr {number} hover-delay\n       */\n      hoverDelay: {\n        type: Number,\n      },\n\n      /**\n       * When true, the tooltip is controlled programmatically\n       * instead of reacting to focus and mouse events.\n       */\n      manual: {\n        type: Boolean,\n        value: false,\n      },\n\n      /**\n       * When true, the tooltip is opened programmatically.\n       * Only works if `manual` is set to `true`.\n       */\n      opened: {\n        type: Boolean,\n        value: false,\n      },\n\n      /**\n       * Position of the tooltip with respect to its target.\n       * Supported values: `top-start`, `top`, `top-end`,\n       * `bottom-start`, `bottom`, `bottom-end`, `start-top`,\n       * `start`, `start-bottom`, `end-top`, `end`, `end-bottom`.\n       */\n      position: {\n        type: String,\n      },\n\n      /**\n       * Function used to detect whether to show the tooltip based on a condition,\n       * called every time the tooltip is about to be shown on hover and focus.\n       * The function takes two parameters: `target` and `context`, which contain\n       * values of the corresponding tooltip properties at the time of calling.\n       * The tooltip is only shown when the function invocation returns `true`.\n       */\n      shouldShow: {\n        type: Object,\n        value: () => {\n          return (_target, _context) => true;\n        },\n      },\n\n      /**\n       * Reference to the element used as a tooltip trigger.\n       * The target must be placed in the same shadow scope.\n       * Defaults to an element referenced with `for`.\n       */\n      target: {\n        type: Object,\n        observer: '__targetChanged',\n      },\n\n      /**\n       * String used as a tooltip content.\n       */\n      text: {\n        type: String,\n        observer: '__textChanged',\n      },\n\n      /**\n       * Function used to generate the tooltip content.\n       * When provided, it overrides the `text` property.\n       * Use the `context` property to provide argument\n       * that can be passed to the generator function.\n       */\n      generator: {\n        type: Object,\n      },\n\n      /**\n       * Set to true when the overlay is opened using auto-added\n       * event listeners: mouseenter and focusin (keyboard only).\n       * @protected\n       */\n      _autoOpened: {\n        type: Boolean,\n        observer: '__autoOpenedChanged',\n      },\n\n      /**\n       * Default value used when `position` property is not set.\n       * @protected\n       */\n      _position: {\n        type: String,\n        value: 'bottom',\n      },\n\n      /** @private */\n      __effectivePosition: {\n        type: String,\n        computed: '__computePosition(position, _position)',\n      },\n\n      /** @private */\n      __isTargetHidden: {\n        type: Boolean,\n        value: false,\n      },\n\n      /** @private */\n      _isConnected: {\n        type: Boolean,\n      },\n    };\n  }\n\n  static get observers() {\n    return ['__generatorChanged(_overlayElement, generator, context)'];\n  }\n\n  /**\n   * Sets the default focus delay to be used by all tooltip instances,\n   * except for those that have focus delay configured using property.\n   *\n   * @param {number} delay\n   */\n  static setDefaultFocusDelay(focusDelay) {\n    defaultFocusDelay = focusDelay != null && focusDelay >= 0 ? focusDelay : DEFAULT_DELAY;\n  }\n\n  /**\n   * Sets the default hide delay to be used by all tooltip instances,\n   * except for those that have hide delay configured using property.\n   *\n   * @param {number} hideDelay\n   */\n  static setDefaultHideDelay(hideDelay) {\n    defaultHideDelay = hideDelay != null && hideDelay >= 0 ? hideDelay : DEFAULT_DELAY;\n  }\n\n  /**\n   * Sets the default hover delay to be used by all tooltip instances,\n   * except for those that have hover delay configured using property.\n   *\n   * @param {number} delay\n   */\n  static setDefaultHoverDelay(hoverDelay) {\n    defaultHoverDelay = hoverDelay != null && hoverDelay >= 0 ? hoverDelay : DEFAULT_DELAY;\n  }\n\n  constructor() {\n    super();\n\n    this._uniqueId = `vaadin-tooltip-${generateUniqueId()}`;\n    this._renderer = this.__tooltipRenderer.bind(this);\n\n    this.__onFocusin = this.__onFocusin.bind(this);\n    this.__onFocusout = this.__onFocusout.bind(this);\n    this.__onMouseDown = this.__onMouseDown.bind(this);\n    this.__onMouseEnter = this.__onMouseEnter.bind(this);\n    this.__onMouseLeave = this.__onMouseLeave.bind(this);\n    this.__onKeyDown = this.__onKeyDown.bind(this);\n    this.__onOverlayOpen = this.__onOverlayOpen.bind(this);\n\n    this.__targetVisibilityObserver = new IntersectionObserver(\n      (entries) => {\n        entries.forEach((entry) => this.__onTargetVisibilityChange(entry.isIntersecting));\n      },\n      { threshold: 0 },\n    );\n\n    this._stateController = new TooltipStateController(this);\n  }\n\n  /** @protected */\n  connectedCallback() {\n    super.connectedCallback();\n\n    this._isConnected = true;\n\n    document.body.addEventListener('vaadin-overlay-open', this.__onOverlayOpen);\n  }\n\n  /** @protected */\n  disconnectedCallback() {\n    super.disconnectedCallback();\n\n    if (this._autoOpened) {\n      this._stateController.close(true);\n    }\n    this._isConnected = false;\n\n    document.body.removeEventListener('vaadin-overlay-open', this.__onOverlayOpen);\n  }\n\n  /** @private */\n  __computeHorizontalAlign(position) {\n    return ['top-end', 'bottom-end', 'start-top', 'start', 'start-bottom'].includes(position) ? 'end' : 'start';\n  }\n\n  /** @private */\n  __computeNoHorizontalOverlap(position) {\n    return ['start-top', 'start', 'start-bottom', 'end-top', 'end', 'end-bottom'].includes(position);\n  }\n\n  /** @private */\n  __computeNoVerticalOverlap(position) {\n    return ['top-start', 'top-end', 'top', 'bottom-start', 'bottom', 'bottom-end'].includes(position);\n  }\n\n  /** @private */\n  __computeVerticalAlign(position) {\n    return ['top-start', 'top-end', 'top', 'start-bottom', 'end-bottom'].includes(position) ? 'bottom' : 'top';\n  }\n\n  /** @private */\n  __computeOpened(manual, opened, autoOpened, connected) {\n    return connected && (manual ? opened : autoOpened);\n  }\n\n  /** @private */\n  __computePosition(position, defaultPosition) {\n    return position || defaultPosition;\n  }\n\n  /** @private */\n  __tooltipRenderer(root) {\n    root.textContent = typeof this.generator === 'function' ? this.generator(this.context) : this.text;\n  }\n\n  /** @private */\n  __autoOpenedChanged(opened, oldOpened) {\n    if (opened) {\n      document.addEventListener('keydown', this.__onKeyDown, true);\n    } else if (oldOpened) {\n      document.removeEventListener('keydown', this.__onKeyDown, true);\n    }\n  }\n\n  /** @private */\n  __forChanged(forId) {\n    if (forId) {\n      this.__setTargetByIdDebouncer = Debouncer.debounce(this.__setTargetByIdDebouncer, microTask, () =>\n        this.__setTargetById(forId),\n      );\n    }\n  }\n\n  /** @private */\n  __setTargetById(targetId) {\n    if (!this.isConnected) {\n      return;\n    }\n\n    const target = this.getRootNode().getElementById(targetId);\n\n    if (target) {\n      this.target = target;\n    } else {\n      console.warn(`No element with id=\"${targetId}\" found to show tooltip.`);\n    }\n  }\n\n  /** @private */\n  __targetChanged(target, oldTarget) {\n    if (oldTarget) {\n      oldTarget.removeEventListener('mouseenter', this.__onMouseEnter);\n      oldTarget.removeEventListener('mouseleave', this.__onMouseLeave);\n      oldTarget.removeEventListener('focusin', this.__onFocusin);\n      oldTarget.removeEventListener('focusout', this.__onFocusout);\n      oldTarget.removeEventListener('mousedown', this.__onMouseDown);\n\n      this.__targetVisibilityObserver.unobserve(oldTarget);\n\n      removeValueFromAttribute(oldTarget, 'aria-describedby', this._uniqueId);\n    }\n\n    if (target) {\n      target.addEventListener('mouseenter', this.__onMouseEnter);\n      target.addEventListener('mouseleave', this.__onMouseLeave);\n      target.addEventListener('focusin', this.__onFocusin);\n      target.addEventListener('focusout', this.__onFocusout);\n      target.addEventListener('mousedown', this.__onMouseDown);\n\n      // Wait before observing to avoid Chrome issue.\n      requestAnimationFrame(() => {\n        this.__targetVisibilityObserver.observe(target);\n      });\n\n      addValueToAttribute(target, 'aria-describedby', this._uniqueId);\n    }\n  }\n\n  /** @private */\n  __onFocusin(event) {\n    if (this.manual) {\n      return;\n    }\n\n    // Only open on keyboard focus.\n    if (!isKeyboardActive()) {\n      return;\n    }\n\n    // Do not re-open while focused if closed on Esc or mousedown.\n    if (this.target.contains(event.relatedTarget)) {\n      return;\n    }\n\n    if (!this.__isShouldShow()) {\n      return;\n    }\n\n    this.__focusInside = true;\n\n    if (!this.__isTargetHidden && (!this.__hoverInside || !this._autoOpened)) {\n      this._stateController.open({ focus: true });\n    }\n  }\n\n  /** @private */\n  __onFocusout(event) {\n    if (this.manual) {\n      return;\n    }\n\n    // Do not close when moving focus within a component.\n    if (this.target.contains(event.relatedTarget)) {\n      return;\n    }\n\n    this.__focusInside = false;\n\n    if (!this.__hoverInside) {\n      this._stateController.close(true);\n    }\n  }\n\n  /** @private */\n  __onKeyDown(event) {\n    if (event.key === 'Escape') {\n      event.stopPropagation();\n      this._stateController.close(true);\n    }\n  }\n\n  /** @private */\n  __onMouseDown() {\n    this._stateController.close(true);\n  }\n\n  /** @private */\n  __onMouseEnter() {\n    if (this.manual) {\n      return;\n    }\n\n    if (!this.__isShouldShow()) {\n      return;\n    }\n\n    if (this.__hoverInside) {\n      // Already hovering inside the element, do nothing.\n      return;\n    }\n\n    this.__hoverInside = true;\n\n    if (!this.__isTargetHidden && (!this.__focusInside || !this._autoOpened)) {\n      this._stateController.open({ hover: true });\n    }\n  }\n\n  /** @private */\n  __onMouseLeave(event) {\n    if (event.relatedTarget !== this._overlayElement) {\n      this.__handleMouseLeave();\n    }\n  }\n\n  /** @private */\n  __onOverlayMouseLeave(event) {\n    if (event.relatedTarget !== this.target) {\n      this.__handleMouseLeave();\n    }\n  }\n\n  /** @private */\n  __handleMouseLeave() {\n    if (this.manual) {\n      return;\n    }\n\n    this.__hoverInside = false;\n\n    if (!this.__focusInside) {\n      this._stateController.close();\n    }\n  }\n\n  /** @private */\n  __onOverlayOpen() {\n    if (this.manual) {\n      return;\n    }\n\n    // Close tooltip if another overlay is opened on top of the tooltip's overlay\n    if (this._overlayElement.opened && !this._overlayElement._last) {\n      this._stateController.close(true);\n    }\n  }\n\n  /** @private */\n  __onTargetVisibilityChange(isVisible) {\n    const oldHidden = this.__isTargetHidden;\n    this.__isTargetHidden = !isVisible;\n\n    // Open the overlay when the target becomes visible and has focus or hover.\n    if (oldHidden && isVisible && (this.__focusInside || this.__hoverInside)) {\n      this._stateController.open({ immediate: true });\n      return;\n    }\n\n    // Close the overlay when the target is no longer fully visible.\n    if (!isVisible && this._autoOpened) {\n      this._stateController.close(true);\n    }\n  }\n\n  /** @private */\n  __isShouldShow() {\n    if (typeof this.shouldShow === 'function' && this.shouldShow(this.target, this.context) !== true) {\n      return false;\n    }\n\n    return true;\n  }\n\n  /** @private */\n  __textChanged(text, oldText) {\n    if (this._overlayElement && (text || oldText)) {\n      this._overlayElement.requestContentUpdate();\n    }\n  }\n\n  /** @private */\n  __generatorChanged(overlayElement, generator, context) {\n    if (overlayElement) {\n      if (generator !== this.__oldTextGenerator || context !== this.__oldContext) {\n        overlayElement.requestContentUpdate();\n      }\n\n      this.__oldTextGenerator = generator;\n      this.__oldContext = context;\n    }\n  }\n}\n\ncustomElements.define(Tooltip.is, Tooltip);\n\nexport { Tooltip };\n","// Clamps a value between an upper and lower bound.\n// We use ternary operators because it makes the minified code\n// 2 times shorter then `Math.min(Math.max(a,b),c)`\nexport const clamp = (number, min = 0, max = 1) => {\n    return number > max ? max : number < min ? min : number;\n};\nexport const round = (number, digits = 0, base = Math.pow(10, digits)) => {\n    return Math.round(base * number) / base;\n};\n//# sourceMappingURL=math.js.map","import { round } from './math.js';\n/**\n * Valid CSS <angle> units.\n * https://developer.mozilla.org/en-US/docs/Web/CSS/angle\n */\nconst angleUnits = {\n    grad: 360 / 400,\n    turn: 360,\n    rad: 360 / (Math.PI * 2)\n};\nexport const hexToHsva = (hex) => rgbaToHsva(hexToRgba(hex));\nexport const hexToRgba = (hex) => {\n    if (hex[0] === '#')\n        hex = hex.substring(1);\n    if (hex.length < 6) {\n        return {\n            r: parseInt(hex[0] + hex[0], 16),\n            g: parseInt(hex[1] + hex[1], 16),\n            b: parseInt(hex[2] + hex[2], 16),\n            a: hex.length === 4 ? round(parseInt(hex[3] + hex[3], 16) / 255, 2) : 1\n        };\n    }\n    return {\n        r: parseInt(hex.substring(0, 2), 16),\n        g: parseInt(hex.substring(2, 4), 16),\n        b: parseInt(hex.substring(4, 6), 16),\n        a: hex.length === 8 ? round(parseInt(hex.substring(6, 8), 16) / 255, 2) : 1\n    };\n};\nexport const parseHue = (value, unit = 'deg') => {\n    return Number(value) * (angleUnits[unit] || 1);\n};\nexport const hslaStringToHsva = (hslString) => {\n    const matcher = /hsla?\\(?\\s*(-?\\d*\\.?\\d+)(deg|rad|grad|turn)?[,\\s]+(-?\\d*\\.?\\d+)%?[,\\s]+(-?\\d*\\.?\\d+)%?,?\\s*[/\\s]*(-?\\d*\\.?\\d+)?(%)?\\s*\\)?/i;\n    const match = matcher.exec(hslString);\n    if (!match)\n        return { h: 0, s: 0, v: 0, a: 1 };\n    return hslaToHsva({\n        h: parseHue(match[1], match[2]),\n        s: Number(match[3]),\n        l: Number(match[4]),\n        a: match[5] === undefined ? 1 : Number(match[5]) / (match[6] ? 100 : 1)\n    });\n};\nexport const hslStringToHsva = hslaStringToHsva;\nexport const hslaToHsva = ({ h, s, l, a }) => {\n    s *= (l < 50 ? l : 100 - l) / 100;\n    return {\n        h: h,\n        s: s > 0 ? ((2 * s) / (l + s)) * 100 : 0,\n        v: l + s,\n        a\n    };\n};\nexport const hsvaToHex = (hsva) => rgbaToHex(hsvaToRgba(hsva));\nexport const hsvaToHsla = ({ h, s, v, a }) => {\n    const hh = ((200 - s) * v) / 100;\n    return {\n        h: round(h),\n        s: round(hh > 0 && hh < 200 ? ((s * v) / 100 / (hh <= 100 ? hh : 200 - hh)) * 100 : 0),\n        l: round(hh / 2),\n        a: round(a, 2)\n    };\n};\nexport const hsvaToHsvString = (hsva) => {\n    const { h, s, v } = roundHsva(hsva);\n    return `hsv(${h}, ${s}%, ${v}%)`;\n};\nexport const hsvaToHsvaString = (hsva) => {\n    const { h, s, v, a } = roundHsva(hsva);\n    return `hsva(${h}, ${s}%, ${v}%, ${a})`;\n};\nexport const hsvaToHslString = (hsva) => {\n    const { h, s, l } = hsvaToHsla(hsva);\n    return `hsl(${h}, ${s}%, ${l}%)`;\n};\nexport const hsvaToHslaString = (hsva) => {\n    const { h, s, l, a } = hsvaToHsla(hsva);\n    return `hsla(${h}, ${s}%, ${l}%, ${a})`;\n};\nexport const hsvaToRgba = ({ h, s, v, a }) => {\n    h = (h / 360) * 6;\n    s = s / 100;\n    v = v / 100;\n    const hh = Math.floor(h), b = v * (1 - s), c = v * (1 - (h - hh) * s), d = v * (1 - (1 - h + hh) * s), module = hh % 6;\n    return {\n        r: round([v, c, b, b, d, v][module] * 255),\n        g: round([d, v, v, c, b, b][module] * 255),\n        b: round([b, b, d, v, v, c][module] * 255),\n        a: round(a, 2)\n    };\n};\nexport const hsvaToRgbString = (hsva) => {\n    const { r, g, b } = hsvaToRgba(hsva);\n    return `rgb(${r}, ${g}, ${b})`;\n};\nexport const hsvaToRgbaString = (hsva) => {\n    const { r, g, b, a } = hsvaToRgba(hsva);\n    return `rgba(${r}, ${g}, ${b}, ${a})`;\n};\nexport const hsvaStringToHsva = (hsvString) => {\n    const matcher = /hsva?\\(?\\s*(-?\\d*\\.?\\d+)(deg|rad|grad|turn)?[,\\s]+(-?\\d*\\.?\\d+)%?[,\\s]+(-?\\d*\\.?\\d+)%?,?\\s*[/\\s]*(-?\\d*\\.?\\d+)?(%)?\\s*\\)?/i;\n    const match = matcher.exec(hsvString);\n    if (!match)\n        return { h: 0, s: 0, v: 0, a: 1 };\n    return roundHsva({\n        h: parseHue(match[1], match[2]),\n        s: Number(match[3]),\n        v: Number(match[4]),\n        a: match[5] === undefined ? 1 : Number(match[5]) / (match[6] ? 100 : 1)\n    });\n};\nexport const hsvStringToHsva = hsvaStringToHsva;\nexport const rgbaStringToHsva = (rgbaString) => {\n    const matcher = /rgba?\\(?\\s*(-?\\d*\\.?\\d+)(%)?[,\\s]+(-?\\d*\\.?\\d+)(%)?[,\\s]+(-?\\d*\\.?\\d+)(%)?,?\\s*[/\\s]*(-?\\d*\\.?\\d+)?(%)?\\s*\\)?/i;\n    const match = matcher.exec(rgbaString);\n    if (!match)\n        return { h: 0, s: 0, v: 0, a: 1 };\n    return rgbaToHsva({\n        r: Number(match[1]) / (match[2] ? 100 / 255 : 1),\n        g: Number(match[3]) / (match[4] ? 100 / 255 : 1),\n        b: Number(match[5]) / (match[6] ? 100 / 255 : 1),\n        a: match[7] === undefined ? 1 : Number(match[7]) / (match[8] ? 100 : 1)\n    });\n};\nexport const rgbStringToHsva = rgbaStringToHsva;\nconst format = (number) => {\n    const hex = number.toString(16);\n    return hex.length < 2 ? '0' + hex : hex;\n};\nexport const rgbaToHex = ({ r, g, b, a }) => {\n    const alphaHex = a < 1 ? format(round(a * 255)) : '';\n    return '#' + format(r) + format(g) + format(b) + alphaHex;\n};\nexport const rgbaToHsva = ({ r, g, b, a }) => {\n    const max = Math.max(r, g, b);\n    const delta = max - Math.min(r, g, b);\n    // prettier-ignore\n    const hh = delta\n        ? max === r\n            ? (g - b) / delta\n            : max === g\n                ? 2 + (b - r) / delta\n                : 4 + (r - g) / delta\n        : 0;\n    return {\n        h: round(60 * (hh < 0 ? hh + 6 : hh)),\n        s: round(max ? (delta / max) * 100 : 0),\n        v: round((max / 255) * 100),\n        a\n    };\n};\nexport const roundHsva = (hsva) => ({\n    h: round(hsva.h),\n    s: round(hsva.s),\n    v: round(hsva.v),\n    a: round(hsva.a, 2)\n});\nexport const rgbaToRgb = ({ r, g, b }) => ({ r, g, b });\nexport const hslaToHsl = ({ h, s, l }) => ({ h, s, l });\nexport const hsvaToHsv = (hsva) => {\n    const { h, s, v } = roundHsva(hsva);\n    return { h, s, v };\n};\n//# sourceMappingURL=convert.js.map","import { hexToRgba } from './convert.js';\nexport const equalColorObjects = (first, second) => {\n    if (first === second)\n        return true;\n    for (const prop in first) {\n        // The following allows for a type-safe calling of this function (first & second have to be HSL, HSV, or RGB)\n        // with type-unsafe iterating over object keys. TS does not allow this without an index (`[key: string]: number`)\n        // on an object to define how iteration is normally done. To ensure extra keys are not allowed on our types,\n        // we must cast our object to unknown (as RGB demands `r` be a key, while `Record<string, x>` does not care if\n        // there is or not), and then as a type TS can iterate over.\n        if (first[prop] !==\n            second[prop])\n            return false;\n    }\n    return true;\n};\nexport const equalColorString = (first, second) => {\n    return first.replace(/\\s/g, '') === second.replace(/\\s/g, '');\n};\nexport const equalHex = (first, second) => {\n    if (first.toLowerCase() === second.toLowerCase())\n        return true;\n    // To compare colors like `#FFF` and `ffffff` we convert them into RGB objects\n    return equalColorObjects(hexToRgba(first), hexToRgba(second));\n};\n//# sourceMappingURL=compare.js.map","const cache = {};\nexport const tpl = (html) => {\n    let template = cache[html];\n    if (!template) {\n        template = document.createElement('template');\n        template.innerHTML = html;\n        cache[html] = template;\n    }\n    return template;\n};\nexport const fire = (target, type, detail) => {\n    target.dispatchEvent(new CustomEvent(type, {\n        bubbles: true,\n        detail\n    }));\n};\n//# sourceMappingURL=dom.js.map","import { fire, tpl } from '../utils/dom.js';\nimport { clamp } from '../utils/math.js';\nlet hasTouched = false;\n// Check if an event was triggered by touch\nconst isTouch = (e) => 'touches' in e;\n// Prevent mobile browsers from handling mouse events (conflicting with touch ones).\n// If we detected a touch interaction before, we prefer reacting to touch events only.\nconst isValid = (event) => {\n    if (hasTouched && !isTouch(event))\n        return false;\n    if (!hasTouched)\n        hasTouched = isTouch(event);\n    return true;\n};\nconst pointerMove = (target, event) => {\n    const pointer = isTouch(event) ? event.touches[0] : event;\n    const rect = target.el.getBoundingClientRect();\n    fire(target.el, 'move', target.getMove({\n        x: clamp((pointer.pageX - (rect.left + window.pageXOffset)) / rect.width),\n        y: clamp((pointer.pageY - (rect.top + window.pageYOffset)) / rect.height)\n    }));\n};\nconst keyMove = (target, event) => {\n    // We use `keyCode` instead of `key` to reduce the size of the library.\n    const keyCode = event.keyCode;\n    // Ignore all keys except arrow ones, Page Up, Page Down, Home and End.\n    if (keyCode > 40 || (target.xy && keyCode < 37) || keyCode < 33)\n        return;\n    // Do not scroll page by keys when color picker element has focus.\n    event.preventDefault();\n    // Send relative offset to the parent component.\n    fire(target.el, 'move', target.getMove({\n        x: keyCode === 39 // Arrow Right\n            ? 0.01\n            : keyCode === 37 // Arrow Left\n                ? -0.01\n                : keyCode === 34 // Page Down\n                    ? 0.05\n                    : keyCode === 33 // Page Up\n                        ? -0.05\n                        : keyCode === 35 // End\n                            ? 1\n                            : keyCode === 36 // Home\n                                ? -1\n                                : 0,\n        y: keyCode === 40 // Arrow down\n            ? 0.01\n            : keyCode === 38 // Arrow Up\n                ? -0.01\n                : 0\n    }, true));\n};\nexport class Slider {\n    constructor(root, part, aria, xy) {\n        const template = tpl(`<div role=\"slider\" tabindex=\"0\" part=\"${part}\" ${aria}><div part=\"${part}-pointer\"></div></div>`);\n        root.appendChild(template.content.cloneNode(true));\n        const el = root.querySelector(`[part=${part}]`);\n        el.addEventListener('mousedown', this);\n        el.addEventListener('touchstart', this);\n        el.addEventListener('keydown', this);\n        this.el = el;\n        this.xy = xy;\n        this.nodes = [el.firstChild, el];\n    }\n    set dragging(state) {\n        const toggleEvent = state ? document.addEventListener : document.removeEventListener;\n        toggleEvent(hasTouched ? 'touchmove' : 'mousemove', this);\n        toggleEvent(hasTouched ? 'touchend' : 'mouseup', this);\n    }\n    handleEvent(event) {\n        switch (event.type) {\n            case 'mousedown':\n            case 'touchstart':\n                event.preventDefault();\n                // event.button is 0 in mousedown for left button activation\n                if (!isValid(event) || (!hasTouched && event.button != 0))\n                    return;\n                this.el.focus();\n                pointerMove(this, event);\n                this.dragging = true;\n                break;\n            case 'mousemove':\n            case 'touchmove':\n                event.preventDefault();\n                pointerMove(this, event);\n                break;\n            case 'mouseup':\n            case 'touchend':\n                this.dragging = false;\n                break;\n            case 'keydown':\n                keyMove(this, event);\n                break;\n        }\n    }\n    style(styles) {\n        styles.forEach((style, i) => {\n            for (const p in style) {\n                this.nodes[i].style.setProperty(p, style[p]);\n            }\n        });\n    }\n}\n//# sourceMappingURL=slider.js.map","import { Slider } from './slider.js';\nimport { hsvaToHslString } from '../utils/convert.js';\nimport { clamp, round } from '../utils/math.js';\nexport class Hue extends Slider {\n    constructor(root) {\n        super(root, 'hue', 'aria-label=\"Hue\" aria-valuemin=\"0\" aria-valuemax=\"360\"', false);\n    }\n    update({ h }) {\n        this.h = h;\n        this.style([\n            {\n                left: `${(h / 360) * 100}%`,\n                color: hsvaToHslString({ h, s: 100, v: 100, a: 1 })\n            }\n        ]);\n        this.el.setAttribute('aria-valuenow', `${round(h)}`);\n    }\n    getMove(offset, key) {\n        // Hue measured in degrees of the color circle ranging from 0 to 360\n        return { h: key ? clamp(this.h + offset.x * 360, 0, 360) : 360 * offset.x };\n    }\n}\n//# sourceMappingURL=hue.js.map","import { Slider } from './slider.js';\nimport { hsvaToHslString } from '../utils/convert.js';\nimport { clamp, round } from '../utils/math.js';\nexport class Saturation extends Slider {\n    constructor(root) {\n        super(root, 'saturation', 'aria-label=\"Color\"', true);\n    }\n    update(hsva) {\n        this.hsva = hsva;\n        this.style([\n            {\n                top: `${100 - hsva.v}%`,\n                left: `${hsva.s}%`,\n                color: hsvaToHslString(hsva)\n            },\n            {\n                'background-color': hsvaToHslString({ h: hsva.h, s: 100, v: 100, a: 1 })\n            }\n        ]);\n        this.el.setAttribute('aria-valuetext', `Saturation ${round(hsva.s)}%, Brightness ${round(hsva.v)}%`);\n    }\n    getMove(offset, key) {\n        // Saturation and brightness always fit into [0, 100] range\n        return {\n            s: key ? clamp(this.hsva.s + offset.x * 100, 0, 100) : offset.x * 100,\n            v: key ? clamp(this.hsva.v - offset.y * 100, 0, 100) : Math.round(100 - offset.y * 100)\n        };\n    }\n}\n//# sourceMappingURL=saturation.js.map","import { equalColorObjects } from '../utils/compare.js';\nimport { fire, tpl } from '../utils/dom.js';\nimport { Hue } from './hue.js';\nimport { Saturation } from './saturation.js';\nimport css from '../styles/color-picker.js';\nimport hueCss from '../styles/hue.js';\nimport saturationCss from '../styles/saturation.js';\nconst $isSame = Symbol('same');\nconst $color = Symbol('color');\nconst $hsva = Symbol('hsva');\nconst $update = Symbol('update');\nconst $parts = Symbol('parts');\nexport const $css = Symbol('css');\nexport const $sliders = Symbol('sliders');\nexport class ColorPicker extends HTMLElement {\n    static get observedAttributes() {\n        return ['color'];\n    }\n    get [$css]() {\n        return [css, hueCss, saturationCss];\n    }\n    get [$sliders]() {\n        return [Saturation, Hue];\n    }\n    get color() {\n        return this[$color];\n    }\n    set color(newColor) {\n        if (!this[$isSame](newColor)) {\n            const newHsva = this.colorModel.toHsva(newColor);\n            this[$update](newHsva);\n            this[$color] = newColor;\n        }\n    }\n    constructor() {\n        super();\n        const template = tpl(`<style>${this[$css].join('')}</style>`);\n        const root = this.attachShadow({ mode: 'open' });\n        root.appendChild(template.content.cloneNode(true));\n        root.addEventListener('move', this);\n        this[$parts] = this[$sliders].map((slider) => new slider(root));\n    }\n    connectedCallback() {\n        // A user may set a property on an _instance_ of an element,\n        // before its prototype has been connected to this class.\n        // If so, we need to run it through the proper class setter.\n        if (this.hasOwnProperty('color')) {\n            const value = this.color;\n            delete this['color'];\n            this.color = value;\n        }\n        else if (!this.color) {\n            this.color = this.colorModel.defaultColor;\n        }\n    }\n    attributeChangedCallback(_attr, _oldVal, newVal) {\n        const color = this.colorModel.fromAttr(newVal);\n        if (!this[$isSame](color)) {\n            this.color = color;\n        }\n    }\n    handleEvent(event) {\n        // Merge the current HSV color object with updated params.\n        const oldHsva = this[$hsva];\n        const newHsva = { ...oldHsva, ...event.detail };\n        this[$update](newHsva);\n        let newColor;\n        if (!equalColorObjects(newHsva, oldHsva) &&\n            !this[$isSame]((newColor = this.colorModel.fromHsva(newHsva)))) {\n            this[$color] = newColor;\n            fire(this, 'color-changed', { value: newColor });\n        }\n    }\n    [$isSame](color) {\n        return this.color && this.colorModel.equal(color, this.color);\n    }\n    [$update](hsva) {\n        this[$hsva] = hsva;\n        this[$parts].forEach((part) => part.update(hsva));\n    }\n}\n//# sourceMappingURL=color-picker.js.map","export default `:host{display:flex;flex-direction:column;position:relative;width:200px;height:200px;user-select:none;-webkit-user-select:none;cursor:default}:host([hidden]){display:none!important}[role=slider]{position:relative;touch-action:none;user-select:none;-webkit-user-select:none;outline:0}[role=slider]:last-child{border-radius:0 0 8px 8px}[part$=pointer]{position:absolute;z-index:1;box-sizing:border-box;width:28px;height:28px;display:flex;place-content:center center;transform:translate(-50%,-50%);background-color:#fff;border:2px solid #fff;border-radius:50%;box-shadow:0 2px 4px rgba(0,0,0,.2)}[part$=pointer]::after{content:\"\";width:100%;height:100%;border-radius:inherit;background-color:currentColor}[role=slider]:focus [part$=pointer]{transform:translate(-50%,-50%) scale(1.1)}`;\n//# sourceMappingURL=color-picker.js.map","export default `[part=hue]{flex:0 0 24px;background:linear-gradient(to right,red 0,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red 100%)}[part=hue-pointer]{top:50%;z-index:2}`;\n//# sourceMappingURL=hue.js.map","export default `[part=saturation]{flex-grow:1;border-color:transparent;border-bottom:12px solid #000;border-radius:8px 8px 0 0;background-image:linear-gradient(to top,#000,transparent),linear-gradient(to right,#fff,rgba(255,255,255,0));box-shadow:inset 0 0 0 1px rgba(0,0,0,.05)}[part=saturation-pointer]{z-index:3}`;\n//# sourceMappingURL=saturation.js.map","import { ColorPicker } from '../components/color-picker.js';\nimport { hexToHsva, hsvaToHex } from '../utils/convert.js';\nimport { equalHex } from '../utils/compare.js';\nconst colorModel = {\n    defaultColor: '#000',\n    toHsva: hexToHsva,\n    fromHsva: ({ h, s, v }) => hsvaToHex({ h, s, v, a: 1 }),\n    equal: equalHex,\n    fromAttr: (color) => color\n};\nexport class HexBase extends ColorPicker {\n    get colorModel() {\n        return colorModel;\n    }\n}\n//# sourceMappingURL=hex.js.map","import { HexBase } from './lib/entrypoints/hex.js';\n/**\n * A color picker custom element that uses HEX format.\n *\n * @element hex-color-picker\n *\n * @prop {string} color - Selected color in HEX format.\n * @attr {string} color - Selected color in HEX format.\n *\n * @fires color-changed - Event fired when color property changes.\n *\n * @csspart hue - A hue selector container.\n * @csspart saturation - A saturation selector container\n * @csspart hue-pointer - A hue pointer element.\n * @csspart saturation-pointer - A saturation pointer element.\n */\nexport class HexColorPicker extends HexBase {\n}\ncustomElements.define('hex-color-picker', HexColorPicker);\n//# sourceMappingURL=hex-color-picker.js.map","(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.Bugsnag = f()}})(function(){var define,module,exports;\nvar _$breadcrumbTypes_8 = ['navigation', 'request', 'process', 'log', 'user', 'state', 'error', 'manual'];\n\n// Array#reduce\nvar _$reduce_17 = function (arr, fn, accum) {\n  var val = accum;\n\n  for (var i = 0, len = arr.length; i < len; i++) {\n    val = fn(val, arr[i], i, arr);\n  }\n\n  return val;\n};\n\n/* removed: var _$reduce_17 = require('./reduce'); */; // Array#filter\n\n\nvar _$filter_12 = function (arr, fn) {\n  return _$reduce_17(arr, function (accum, item, i, arr) {\n    return !fn(item, i, arr) ? accum : accum.concat(item);\n  }, []);\n};\n\n/* removed: var _$reduce_17 = require('./reduce'); */; // Array#includes\n\n\nvar _$includes_13 = function (arr, x) {\n  return _$reduce_17(arr, function (accum, item, i, arr) {\n    return accum === true || item === x;\n  }, false);\n};\n\n// Array#isArray\nvar _$isArray_14 = function (obj) {\n  return Object.prototype.toString.call(obj) === '[object Array]';\n};\n\n/* eslint-disable-next-line no-prototype-builtins */\nvar _hasDontEnumBug = !{\n  toString: null\n}.propertyIsEnumerable('toString');\n\nvar _dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor']; // Object#keys\n\nvar _$keys_15 = function (obj) {\n  // stripped down version of\n  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Keys\n  var result = [];\n  var prop;\n\n  for (prop in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, prop)) result.push(prop);\n  }\n\n  if (!_hasDontEnumBug) return result;\n\n  for (var i = 0, len = _dontEnums.length; i < len; i++) {\n    if (Object.prototype.hasOwnProperty.call(obj, _dontEnums[i])) result.push(_dontEnums[i]);\n  }\n\n  return result;\n};\n\nvar _$intRange_24 = function (min, max) {\n  if (min === void 0) {\n    min = 1;\n  }\n\n  if (max === void 0) {\n    max = Infinity;\n  }\n\n  return function (value) {\n    return typeof value === 'number' && parseInt('' + value, 10) === value && value >= min && value <= max;\n  };\n};\n\n/* removed: var _$filter_12 = require('../es-utils/filter'); */;\n\n/* removed: var _$isArray_14 = require('../es-utils/is-array'); */;\n\nvar _$listOfFunctions_25 = function (value) {\n  return typeof value === 'function' || _$isArray_14(value) && _$filter_12(value, function (f) {\n    return typeof f === 'function';\n  }).length === value.length;\n};\n\nvar _$stringWithLength_26 = function (value) {\n  return typeof value === 'string' && !!value.length;\n};\n\nvar _$config_5 = {};\n/* removed: var _$filter_12 = require('./lib/es-utils/filter'); */;\n\n/* removed: var _$reduce_17 = require('./lib/es-utils/reduce'); */;\n\n/* removed: var _$keys_15 = require('./lib/es-utils/keys'); */;\n\n/* removed: var _$isArray_14 = require('./lib/es-utils/is-array'); */;\n\n/* removed: var _$includes_13 = require('./lib/es-utils/includes'); */;\n\n/* removed: var _$intRange_24 = require('./lib/validators/int-range'); */;\n\n/* removed: var _$stringWithLength_26 = require('./lib/validators/string-with-length'); */;\n\n/* removed: var _$listOfFunctions_25 = require('./lib/validators/list-of-functions'); */;\n\n/* removed: var _$breadcrumbTypes_8 = require('./lib/breadcrumb-types'); */;\n\nvar defaultErrorTypes = function () {\n  return {\n    unhandledExceptions: true,\n    unhandledRejections: true\n  };\n};\n\n_$config_5.schema = {\n  apiKey: {\n    defaultValue: function () {\n      return null;\n    },\n    message: 'is required',\n    validate: _$stringWithLength_26\n  },\n  appVersion: {\n    defaultValue: function () {\n      return undefined;\n    },\n    message: 'should be a string',\n    validate: function (value) {\n      return value === undefined || _$stringWithLength_26(value);\n    }\n  },\n  appType: {\n    defaultValue: function () {\n      return undefined;\n    },\n    message: 'should be a string',\n    validate: function (value) {\n      return value === undefined || _$stringWithLength_26(value);\n    }\n  },\n  autoDetectErrors: {\n    defaultValue: function () {\n      return true;\n    },\n    message: 'should be true|false',\n    validate: function (value) {\n      return value === true || value === false;\n    }\n  },\n  enabledErrorTypes: {\n    defaultValue: function () {\n      return defaultErrorTypes();\n    },\n    message: 'should be an object containing the flags { unhandledExceptions:true|false, unhandledRejections:true|false }',\n    allowPartialObject: true,\n    validate: function (value) {\n      // ensure we have an object\n      if (typeof value !== 'object' || !value) return false;\n      var providedKeys = _$keys_15(value);\n      var defaultKeys = _$keys_15(defaultErrorTypes()); // ensure it only has a subset of the allowed keys\n\n      if (_$filter_12(providedKeys, function (k) {\n        return _$includes_13(defaultKeys, k);\n      }).length < providedKeys.length) return false; // ensure all of the values are boolean\n\n      if (_$filter_12(_$keys_15(value), function (k) {\n        return typeof value[k] !== 'boolean';\n      }).length > 0) return false;\n      return true;\n    }\n  },\n  onError: {\n    defaultValue: function () {\n      return [];\n    },\n    message: 'should be a function or array of functions',\n    validate: _$listOfFunctions_25\n  },\n  onSession: {\n    defaultValue: function () {\n      return [];\n    },\n    message: 'should be a function or array of functions',\n    validate: _$listOfFunctions_25\n  },\n  onBreadcrumb: {\n    defaultValue: function () {\n      return [];\n    },\n    message: 'should be a function or array of functions',\n    validate: _$listOfFunctions_25\n  },\n  endpoints: {\n    defaultValue: function () {\n      return {\n        notify: 'https://notify.bugsnag.com',\n        sessions: 'https://sessions.bugsnag.com'\n      };\n    },\n    message: 'should be an object containing endpoint URLs { notify, sessions }',\n    validate: function (val) {\n      return (// first, ensure it's an object\n        val && typeof val === 'object' && // notify and sessions must always be set\n        _$stringWithLength_26(val.notify) && _$stringWithLength_26(val.sessions) && // ensure no keys other than notify/session are set on endpoints object\n        _$filter_12(_$keys_15(val), function (k) {\n          return !_$includes_13(['notify', 'sessions'], k);\n        }).length === 0\n      );\n    }\n  },\n  autoTrackSessions: {\n    defaultValue: function (val) {\n      return true;\n    },\n    message: 'should be true|false',\n    validate: function (val) {\n      return val === true || val === false;\n    }\n  },\n  enabledReleaseStages: {\n    defaultValue: function () {\n      return null;\n    },\n    message: 'should be an array of strings',\n    validate: function (value) {\n      return value === null || _$isArray_14(value) && _$filter_12(value, function (f) {\n        return typeof f === 'string';\n      }).length === value.length;\n    }\n  },\n  releaseStage: {\n    defaultValue: function () {\n      return 'production';\n    },\n    message: 'should be a string',\n    validate: function (value) {\n      return typeof value === 'string' && value.length;\n    }\n  },\n  maxBreadcrumbs: {\n    defaultValue: function () {\n      return 25;\n    },\n    message: 'should be a number ≤100',\n    validate: function (value) {\n      return _$intRange_24(0, 100)(value);\n    }\n  },\n  enabledBreadcrumbTypes: {\n    defaultValue: function () {\n      return _$breadcrumbTypes_8;\n    },\n    message: \"should be null or a list of available breadcrumb types (\" + _$breadcrumbTypes_8.join(',') + \")\",\n    validate: function (value) {\n      return value === null || _$isArray_14(value) && _$reduce_17(value, function (accum, maybeType) {\n        if (accum === false) return accum;\n        return _$includes_13(_$breadcrumbTypes_8, maybeType);\n      }, true);\n    }\n  },\n  context: {\n    defaultValue: function () {\n      return undefined;\n    },\n    message: 'should be a string',\n    validate: function (value) {\n      return value === undefined || typeof value === 'string';\n    }\n  },\n  user: {\n    defaultValue: function () {\n      return {};\n    },\n    message: 'should be an object with { id, email, name } properties',\n    validate: function (value) {\n      return value === null || value && _$reduce_17(_$keys_15(value), function (accum, key) {\n        return accum && _$includes_13(['id', 'email', 'name'], key);\n      }, true);\n    }\n  },\n  metadata: {\n    defaultValue: function () {\n      return {};\n    },\n    message: 'should be an object',\n    validate: function (value) {\n      return typeof value === 'object' && value !== null;\n    }\n  },\n  logger: {\n    defaultValue: function () {\n      return undefined;\n    },\n    message: 'should be null or an object with methods { debug, info, warn, error }',\n    validate: function (value) {\n      return !value || value && _$reduce_17(['debug', 'info', 'warn', 'error'], function (accum, method) {\n        return accum && typeof value[method] === 'function';\n      }, true);\n    }\n  },\n  redactedKeys: {\n    defaultValue: function () {\n      return ['password'];\n    },\n    message: 'should be an array of strings|regexes',\n    validate: function (value) {\n      return _$isArray_14(value) && value.length === _$filter_12(value, function (s) {\n        return typeof s === 'string' || s && typeof s.test === 'function';\n      }).length;\n    }\n  },\n  plugins: {\n    defaultValue: function () {\n      return [];\n    },\n    message: 'should be an array of plugin objects',\n    validate: function (value) {\n      return _$isArray_14(value) && value.length === _$filter_12(value, function (p) {\n        return p && typeof p === 'object' && typeof p.load === 'function';\n      }).length;\n    }\n  },\n  featureFlags: {\n    defaultValue: function () {\n      return [];\n    },\n    message: 'should be an array of objects that have a \"name\" property',\n    validate: function (value) {\n      return _$isArray_14(value) && value.length === _$filter_12(value, function (feature) {\n        return feature && typeof feature === 'object' && typeof feature.name === 'string';\n      }).length;\n    }\n  }\n};\n\n// extends helper from babel\n// https://github.com/babel/babel/blob/916429b516e6466fd06588ee820e40e025d7f3a3/packages/babel-helpers/src/helpers.js#L377-L393\nvar _$assign_11 = function (target) {\n  for (var i = 1; i < arguments.length; i++) {\n    var source = arguments[i];\n\n    for (var key in source) {\n      if (Object.prototype.hasOwnProperty.call(source, key)) {\n        target[key] = source[key];\n      }\n    }\n  }\n\n  return target;\n};\n\n/* removed: var _$reduce_17 = require('./reduce'); */; // Array#map\n\n\nvar _$map_16 = function (arr, fn) {\n  return _$reduce_17(arr, function (accum, item, i, arr) {\n    return accum.concat(fn(item, i, arr));\n  }, []);\n};\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nvar schema = _$config_5.schema;\n\n/* removed: var _$map_16 = require('@bugsnag/core/lib/es-utils/map'); */;\n\n/* removed: var _$assign_11 = require('@bugsnag/core/lib/es-utils/assign'); */;\n\nvar _$config_1 = {\n  releaseStage: _$assign_11({}, schema.releaseStage, {\n    defaultValue: function () {\n      if (/^localhost(:\\d+)?$/.test(window.location.host)) return 'development';\n      return 'production';\n    }\n  }),\n  appType: _extends({}, schema.appType, {\n    defaultValue: function () {\n      return 'browser';\n    }\n  }),\n  logger: _$assign_11({}, schema.logger, {\n    defaultValue: function () {\n      return (// set logger based on browser capability\n        typeof console !== 'undefined' && typeof console.debug === 'function' ? getPrefixedConsole() : undefined\n      );\n    }\n  })\n};\n\nvar getPrefixedConsole = function () {\n  var logger = {};\n  var consoleLog = console.log;\n  _$map_16(['debug', 'info', 'warn', 'error'], function (method) {\n    var consoleMethod = console[method];\n    logger[method] = typeof consoleMethod === 'function' ? consoleMethod.bind(console, '[bugsnag]') : consoleLog.bind(console, '[bugsnag]');\n  });\n  return logger;\n};\n\nvar Breadcrumb = /*#__PURE__*/function () {\n  function Breadcrumb(message, metadata, type, timestamp) {\n    if (timestamp === void 0) {\n      timestamp = new Date();\n    }\n\n    this.type = type;\n    this.message = message;\n    this.metadata = metadata;\n    this.timestamp = timestamp;\n  }\n\n  var _proto = Breadcrumb.prototype;\n\n  _proto.toJSON = function toJSON() {\n    return {\n      type: this.type,\n      name: this.message,\n      timestamp: this.timestamp,\n      metaData: this.metadata\n    };\n  };\n\n  return Breadcrumb;\n}();\n\nvar _$Breadcrumb_3 = Breadcrumb;\n\nvar _$stackframe_34 = {};\n(function (root, factory) {\n  'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.\n\n  /* istanbul ignore next */\n\n  if (typeof define === 'function' && define.amd) {\n    define('stackframe', [], factory);\n  } else if (typeof _$stackframe_34 === 'object') {\n    _$stackframe_34 = factory();\n  } else {\n    root.StackFrame = factory();\n  }\n})(this, function () {\n  'use strict';\n\n  function _isNumber(n) {\n    return !isNaN(parseFloat(n)) && isFinite(n);\n  }\n\n  function _capitalize(str) {\n    return str.charAt(0).toUpperCase() + str.substring(1);\n  }\n\n  function _getter(p) {\n    return function () {\n      return this[p];\n    };\n  }\n\n  var booleanProps = ['isConstructor', 'isEval', 'isNative', 'isToplevel'];\n  var numericProps = ['columnNumber', 'lineNumber'];\n  var stringProps = ['fileName', 'functionName', 'source'];\n  var arrayProps = ['args'];\n  var props = booleanProps.concat(numericProps, stringProps, arrayProps);\n\n  function StackFrame(obj) {\n    if (obj instanceof Object) {\n      for (var i = 0; i < props.length; i++) {\n        if (obj.hasOwnProperty(props[i]) && obj[props[i]] !== undefined) {\n          this['set' + _capitalize(props[i])](obj[props[i]]);\n        }\n      }\n    }\n  }\n\n  StackFrame.prototype = {\n    getArgs: function () {\n      return this.args;\n    },\n    setArgs: function (v) {\n      if (Object.prototype.toString.call(v) !== '[object Array]') {\n        throw new TypeError('Args must be an Array');\n      }\n\n      this.args = v;\n    },\n    getEvalOrigin: function () {\n      return this.evalOrigin;\n    },\n    setEvalOrigin: function (v) {\n      if (v instanceof StackFrame) {\n        this.evalOrigin = v;\n      } else if (v instanceof Object) {\n        this.evalOrigin = new StackFrame(v);\n      } else {\n        throw new TypeError('Eval Origin must be an Object or StackFrame');\n      }\n    },\n    toString: function () {\n      var functionName = this.getFunctionName() || '{anonymous}';\n      var args = '(' + (this.getArgs() || []).join(',') + ')';\n      var fileName = this.getFileName() ? '@' + this.getFileName() : '';\n      var lineNumber = _isNumber(this.getLineNumber()) ? ':' + this.getLineNumber() : '';\n      var columnNumber = _isNumber(this.getColumnNumber()) ? ':' + this.getColumnNumber() : '';\n      return functionName + args + fileName + lineNumber + columnNumber;\n    }\n  };\n\n  for (var i = 0; i < booleanProps.length; i++) {\n    StackFrame.prototype['get' + _capitalize(booleanProps[i])] = _getter(booleanProps[i]);\n\n    StackFrame.prototype['set' + _capitalize(booleanProps[i])] = function (p) {\n      return function (v) {\n        this[p] = Boolean(v);\n      };\n    }(booleanProps[i]);\n  }\n\n  for (var j = 0; j < numericProps.length; j++) {\n    StackFrame.prototype['get' + _capitalize(numericProps[j])] = _getter(numericProps[j]);\n\n    StackFrame.prototype['set' + _capitalize(numericProps[j])] = function (p) {\n      return function (v) {\n        if (!_isNumber(v)) {\n          throw new TypeError(p + ' must be a Number');\n        }\n\n        this[p] = Number(v);\n      };\n    }(numericProps[j]);\n  }\n\n  for (var k = 0; k < stringProps.length; k++) {\n    StackFrame.prototype['get' + _capitalize(stringProps[k])] = _getter(stringProps[k]);\n\n    StackFrame.prototype['set' + _capitalize(stringProps[k])] = function (p) {\n      return function (v) {\n        this[p] = String(v);\n      };\n    }(stringProps[k]);\n  }\n\n  return StackFrame;\n});\n\nvar _$errorStackParser_31 = {};\n(function (root, factory) {\n  'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.\n\n  /* istanbul ignore next */\n\n  if (typeof define === 'function' && define.amd) {\n    define('error-stack-parser', ['stackframe'], factory);\n  } else if (typeof _$errorStackParser_31 === 'object') {\n    _$errorStackParser_31 = factory(_$stackframe_34);\n  } else {\n    root.ErrorStackParser = factory(root.StackFrame);\n  }\n})(this, function ErrorStackParser(StackFrame) {\n  'use strict';\n\n  var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\\S+\\:\\d+/;\n  var CHROME_IE_STACK_REGEXP = /^\\s*at .*(\\S+\\:\\d+|\\(native\\))/m;\n  var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\\[native code\\])?$/;\n  return {\n    /**\n     * Given an Error object, extract the most information from it.\n     *\n     * @param {Error} error object\n     * @return {Array} of StackFrames\n     */\n    parse: function ErrorStackParser$$parse(error) {\n      if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') {\n        return this.parseOpera(error);\n      } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {\n        return this.parseV8OrIE(error);\n      } else if (error.stack) {\n        return this.parseFFOrSafari(error);\n      } else {\n        throw new Error('Cannot parse given Error object');\n      }\n    },\n    // Separate line and column numbers from a string of the form: (URI:Line:Column)\n    extractLocation: function ErrorStackParser$$extractLocation(urlLike) {\n      // Fail-fast but return locations like \"(native)\"\n      if (urlLike.indexOf(':') === -1) {\n        return [urlLike];\n      }\n\n      var regExp = /(.+?)(?:\\:(\\d+))?(?:\\:(\\d+))?$/;\n      var parts = regExp.exec(urlLike.replace(/[\\(\\)]/g, ''));\n      return [parts[1], parts[2] || undefined, parts[3] || undefined];\n    },\n    parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) {\n      var filtered = error.stack.split('\\n').filter(function (line) {\n        return !!line.match(CHROME_IE_STACK_REGEXP);\n      }, this);\n      return filtered.map(function (line) {\n        if (line.indexOf('(eval ') > -1) {\n          // Throw away eval information until we implement stacktrace.js/stackframe#8\n          line = line.replace(/eval code/g, 'eval').replace(/(\\(eval at [^\\()]*)|(\\)\\,.*$)/g, '');\n        }\n\n        var sanitizedLine = line.replace(/^\\s+/, '').replace(/\\(eval code/g, '('); // capture and preseve the parenthesized location \"(/foo/my bar.js:12:87)\" in\n        // case it has spaces in it, as the string is split on \\s+ later on\n\n        var location = sanitizedLine.match(/ (\\((.+):(\\d+):(\\d+)\\)$)/); // remove the parenthesized location from the line, if it was matched\n\n        sanitizedLine = location ? sanitizedLine.replace(location[0], '') : sanitizedLine;\n        var tokens = sanitizedLine.split(/\\s+/).slice(1); // if a location was matched, pass it to extractLocation() otherwise pop the last token\n\n        var locationParts = this.extractLocation(location ? location[1] : tokens.pop());\n        var functionName = tokens.join(' ') || undefined;\n        var fileName = ['eval', '<anonymous>'].indexOf(locationParts[0]) > -1 ? undefined : locationParts[0];\n        return new StackFrame({\n          functionName: functionName,\n          fileName: fileName,\n          lineNumber: locationParts[1],\n          columnNumber: locationParts[2],\n          source: line\n        });\n      }, this);\n    },\n    parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) {\n      var filtered = error.stack.split('\\n').filter(function (line) {\n        return !line.match(SAFARI_NATIVE_CODE_REGEXP);\n      }, this);\n      return filtered.map(function (line) {\n        // Throw away eval information until we implement stacktrace.js/stackframe#8\n        if (line.indexOf(' > eval') > -1) {\n          line = line.replace(/ line (\\d+)(?: > eval line \\d+)* > eval\\:\\d+\\:\\d+/g, ':$1');\n        }\n\n        if (line.indexOf('@') === -1 && line.indexOf(':') === -1) {\n          // Safari eval frames only have function names and nothing else\n          return new StackFrame({\n            functionName: line\n          });\n        } else {\n          var functionNameRegex = /((.*\".+\"[^@]*)?[^@]*)(?:@)/;\n          var matches = line.match(functionNameRegex);\n          var functionName = matches && matches[1] ? matches[1] : undefined;\n          var locationParts = this.extractLocation(line.replace(functionNameRegex, ''));\n          return new StackFrame({\n            functionName: functionName,\n            fileName: locationParts[0],\n            lineNumber: locationParts[1],\n            columnNumber: locationParts[2],\n            source: line\n          });\n        }\n      }, this);\n    },\n    parseOpera: function ErrorStackParser$$parseOpera(e) {\n      if (!e.stacktrace || e.message.indexOf('\\n') > -1 && e.message.split('\\n').length > e.stacktrace.split('\\n').length) {\n        return this.parseOpera9(e);\n      } else if (!e.stack) {\n        return this.parseOpera10(e);\n      } else {\n        return this.parseOpera11(e);\n      }\n    },\n    parseOpera9: function ErrorStackParser$$parseOpera9(e) {\n      var lineRE = /Line (\\d+).*script (?:in )?(\\S+)/i;\n      var lines = e.message.split('\\n');\n      var result = [];\n\n      for (var i = 2, len = lines.length; i < len; i += 2) {\n        var match = lineRE.exec(lines[i]);\n\n        if (match) {\n          result.push(new StackFrame({\n            fileName: match[2],\n            lineNumber: match[1],\n            source: lines[i]\n          }));\n        }\n      }\n\n      return result;\n    },\n    parseOpera10: function ErrorStackParser$$parseOpera10(e) {\n      var lineRE = /Line (\\d+).*script (?:in )?(\\S+)(?:: In function (\\S+))?$/i;\n      var lines = e.stacktrace.split('\\n');\n      var result = [];\n\n      for (var i = 0, len = lines.length; i < len; i += 2) {\n        var match = lineRE.exec(lines[i]);\n\n        if (match) {\n          result.push(new StackFrame({\n            functionName: match[3] || undefined,\n            fileName: match[2],\n            lineNumber: match[1],\n            source: lines[i]\n          }));\n        }\n      }\n\n      return result;\n    },\n    // Opera 10.65+ Error.stack very similar to FF/Safari\n    parseOpera11: function ErrorStackParser$$parseOpera11(error) {\n      var filtered = error.stack.split('\\n').filter(function (line) {\n        return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/);\n      }, this);\n      return filtered.map(function (line) {\n        var tokens = line.split('@');\n        var locationParts = this.extractLocation(tokens.pop());\n        var functionCall = tokens.shift() || '';\n        var functionName = functionCall.replace(/<anonymous function(: (\\w+))?>/, '$2').replace(/\\([^\\)]*\\)/g, '') || undefined;\n        var argsRaw;\n\n        if (functionCall.match(/\\(([^\\)]*)\\)/)) {\n          argsRaw = functionCall.replace(/^[^\\(]+\\(([^\\)]*)\\)$/, '$1');\n        }\n\n        var args = argsRaw === undefined || argsRaw === '[arguments not available]' ? undefined : argsRaw.split(',');\n        return new StackFrame({\n          functionName: functionName,\n          args: args,\n          fileName: locationParts[0],\n          lineNumber: locationParts[1],\n          columnNumber: locationParts[2],\n          source: line\n        });\n      }, this);\n    }\n  };\n});\n\nvar _$errorStackParser_10 = _$errorStackParser_31;\n\nvar _$safeJsonStringify_30 = function (data, replacer, space, opts) {\n  var redactedKeys = opts && opts.redactedKeys ? opts.redactedKeys : [];\n  var redactedPaths = opts && opts.redactedPaths ? opts.redactedPaths : [];\n  return JSON.stringify(prepareObjForSerialization(data, redactedKeys, redactedPaths), replacer, space);\n};\n\nvar MAX_DEPTH = 20;\nvar MAX_EDGES = 25000;\nvar MIN_PRESERVED_DEPTH = 8;\nvar REPLACEMENT_NODE = '...';\n\nfunction isError(o) {\n  return o instanceof Error || /^\\[object (Error|(Dom)?Exception)\\]$/.test(Object.prototype.toString.call(o));\n}\n\nfunction throwsMessage(err) {\n  return '[Throws: ' + (err ? err.message : '?') + ']';\n}\n\nfunction find(haystack, needle) {\n  for (var i = 0, len = haystack.length; i < len; i++) {\n    if (haystack[i] === needle) return true;\n  }\n\n  return false;\n} // returns true if the string `path` starts with any of the provided `paths`\n\n\nfunction isDescendent(paths, path) {\n  for (var i = 0, len = paths.length; i < len; i++) {\n    if (path.indexOf(paths[i]) === 0) return true;\n  }\n\n  return false;\n}\n\nfunction shouldRedact(patterns, key) {\n  for (var i = 0, len = patterns.length; i < len; i++) {\n    if (typeof patterns[i] === 'string' && patterns[i].toLowerCase() === key.toLowerCase()) return true;\n    if (patterns[i] && typeof patterns[i].test === 'function' && patterns[i].test(key)) return true;\n  }\n\n  return false;\n}\n\nfunction __isArray_30(obj) {\n  return Object.prototype.toString.call(obj) === '[object Array]';\n}\n\nfunction safelyGetProp(obj, prop) {\n  try {\n    return obj[prop];\n  } catch (err) {\n    return throwsMessage(err);\n  }\n}\n\nfunction prepareObjForSerialization(obj, redactedKeys, redactedPaths) {\n  var seen = []; // store references to objects we have seen before\n\n  var edges = 0;\n\n  function visit(obj, path) {\n    function edgesExceeded() {\n      return path.length > MIN_PRESERVED_DEPTH && edges > MAX_EDGES;\n    }\n\n    edges++;\n    if (path.length > MAX_DEPTH) return REPLACEMENT_NODE;\n    if (edgesExceeded()) return REPLACEMENT_NODE;\n    if (obj === null || typeof obj !== 'object') return obj;\n    if (find(seen, obj)) return '[Circular]';\n    seen.push(obj);\n\n    if (typeof obj.toJSON === 'function') {\n      try {\n        // we're not going to count this as an edge because it\n        // replaces the value of the currently visited object\n        edges--;\n        var fResult = visit(obj.toJSON(), path);\n        seen.pop();\n        return fResult;\n      } catch (err) {\n        return throwsMessage(err);\n      }\n    }\n\n    var er = isError(obj);\n\n    if (er) {\n      edges--;\n      var eResult = visit({\n        name: obj.name,\n        message: obj.message\n      }, path);\n      seen.pop();\n      return eResult;\n    }\n\n    if (__isArray_30(obj)) {\n      var aResult = [];\n\n      for (var i = 0, len = obj.length; i < len; i++) {\n        if (edgesExceeded()) {\n          aResult.push(REPLACEMENT_NODE);\n          break;\n        }\n\n        aResult.push(visit(obj[i], path.concat('[]')));\n      }\n\n      seen.pop();\n      return aResult;\n    }\n\n    var result = {};\n\n    try {\n      for (var prop in obj) {\n        if (!Object.prototype.hasOwnProperty.call(obj, prop)) continue;\n\n        if (isDescendent(redactedPaths, path.join('.')) && shouldRedact(redactedKeys, prop)) {\n          result[prop] = '[REDACTED]';\n          continue;\n        }\n\n        if (edgesExceeded()) {\n          result[prop] = REPLACEMENT_NODE;\n          break;\n        }\n\n        result[prop] = visit(safelyGetProp(obj, prop), path.concat(prop));\n      }\n    } catch (e) {}\n\n    seen.pop();\n    return result;\n  }\n\n  return visit(obj, []);\n}\n\n/* removed: var _$map_16 = require('./es-utils/map'); */;\n\n/* removed: var _$filter_12 = require('./es-utils/filter'); */;\n\n/* removed: var _$isArray_14 = require('./es-utils/is-array'); */;\n\n/* removed: var _$safeJsonStringify_30 = require('@bugsnag/safe-json-stringify'); */;\n\nfunction add(existingFeatures, existingFeatureKeys, name, variant) {\n  if (typeof name !== 'string') {\n    return;\n  }\n\n  if (variant === undefined) {\n    variant = null;\n  } else if (variant !== null && typeof variant !== 'string') {\n    variant = _$safeJsonStringify_30(variant);\n  }\n\n  var existingIndex = existingFeatureKeys[name];\n\n  if (typeof existingIndex === 'number') {\n    existingFeatures[existingIndex] = {\n      name: name,\n      variant: variant\n    };\n    return;\n  }\n\n  existingFeatures.push({\n    name: name,\n    variant: variant\n  });\n  existingFeatureKeys[name] = existingFeatures.length - 1;\n}\n\nfunction merge(existingFeatures, newFeatures, existingFeatureKeys) {\n  if (!_$isArray_14(newFeatures)) {\n    return;\n  }\n\n  for (var i = 0; i < newFeatures.length; ++i) {\n    var feature = newFeatures[i];\n\n    if (feature === null || typeof feature !== 'object') {\n      continue;\n    } // 'add' will handle if 'name' doesn't exist & 'variant' is optional\n\n\n    add(existingFeatures, existingFeatureKeys, feature.name, feature.variant);\n  }\n\n  return existingFeatures;\n} // convert feature flags from a map of 'name -> variant' into the format required\n// by the Bugsnag Event API:\n//   [{ featureFlag: 'name', variant: 'variant' }, { featureFlag: 'name 2' }]\n\n\nfunction toEventApi(featureFlags) {\n  return _$map_16(_$filter_12(featureFlags, Boolean), function (_ref) {\n    var name = _ref.name,\n        variant = _ref.variant;\n    var flag = {\n      featureFlag: name\n    }; // don't add a 'variant' property unless there's actually a value\n\n    if (typeof variant === 'string') {\n      flag.variant = variant;\n    }\n\n    return flag;\n  });\n}\n\nfunction clear(features, featuresIndex, name) {\n  var existingIndex = featuresIndex[name];\n\n  if (typeof existingIndex === 'number') {\n    features[existingIndex] = null;\n    delete featuresIndex[name];\n  }\n}\n\nvar _$featureFlagDelegate_18 = {\n  add: add,\n  clear: clear,\n  merge: merge,\n  toEventApi: toEventApi\n};\n\n// Given `err` which may be an error, does it have a stack property which is a string?\nvar _$hasStack_19 = function (err) {\n  return !!err && (!!err.stack || !!err.stacktrace || !!err['opera#sourceloc']) && typeof (err.stack || err.stacktrace || err['opera#sourceloc']) === 'string' && err.stack !== err.name + \": \" + err.message;\n};\n\n/**\n * Expose `isError`.\n */\nvar _$isError_32 = __isError_32;\n/**\n * Test whether `value` is error object.\n *\n * @param {*} value\n * @returns {boolean}\n */\n\nfunction __isError_32(value) {\n  switch (Object.prototype.toString.call(value)) {\n    case '[object Error]':\n      return true;\n\n    case '[object Exception]':\n      return true;\n\n    case '[object DOMException]':\n      return true;\n\n    default:\n      return value instanceof Error;\n  }\n}\n\nvar _$iserror_20 = _$isError_32;\n\n/* removed: var _$assign_11 = require('./es-utils/assign'); */;\n\nvar __add_22 = function (state, section, keyOrObj, maybeVal) {\n  var _updates;\n\n  if (!section) return;\n  var updates; // addMetadata(\"section\", null) -> clears section\n\n  if (keyOrObj === null) return __clear_22(state, section); // normalise the two supported input types into object form\n\n  if (typeof keyOrObj === 'object') updates = keyOrObj;\n  if (typeof keyOrObj === 'string') updates = (_updates = {}, _updates[keyOrObj] = maybeVal, _updates); // exit if we don't have an updates object at this point\n\n  if (!updates) return; // ensure a section with this name exists\n\n  if (!state[section]) state[section] = {}; // merge the updates with the existing section\n\n  state[section] = _$assign_11({}, state[section], updates);\n};\n\nvar get = function (state, section, key) {\n  if (typeof section !== 'string') return undefined;\n\n  if (!key) {\n    return state[section];\n  }\n\n  if (state[section]) {\n    return state[section][key];\n  }\n\n  return undefined;\n};\n\nvar __clear_22 = function (state, section, key) {\n  if (typeof section !== 'string') return; // clear an entire section\n\n  if (!key) {\n    delete state[section];\n    return;\n  } // clear a single value from a section\n\n\n  if (state[section]) {\n    delete state[section][key];\n  }\n};\n\nvar _$metadataDelegate_22 = {\n  add: __add_22,\n  get: get,\n  clear: __clear_22\n};\n\nvar _$stackGenerator_33 = {};\n(function (root, factory) {\n  'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.\n\n  /* istanbul ignore next */\n\n  if (typeof define === 'function' && define.amd) {\n    define('stack-generator', ['stackframe'], factory);\n  } else if (typeof _$stackGenerator_33 === 'object') {\n    _$stackGenerator_33 = factory(_$stackframe_34);\n  } else {\n    root.StackGenerator = factory(root.StackFrame);\n  }\n})(this, function (StackFrame) {\n  return {\n    backtrace: function StackGenerator$$backtrace(opts) {\n      var stack = [];\n      var maxStackSize = 10;\n\n      if (typeof opts === 'object' && typeof opts.maxStackSize === 'number') {\n        maxStackSize = opts.maxStackSize;\n      }\n\n      var curr = arguments.callee;\n\n      while (curr && stack.length < maxStackSize && curr['arguments']) {\n        // Allow V8 optimizations\n        var args = new Array(curr['arguments'].length);\n\n        for (var i = 0; i < args.length; ++i) {\n          args[i] = curr['arguments'][i];\n        }\n\n        if (/function(?:\\s+([\\w$]+))+\\s*\\(/.test(curr.toString())) {\n          stack.push(new StackFrame({\n            functionName: RegExp.$1 || undefined,\n            args: args\n          }));\n        } else {\n          stack.push(new StackFrame({\n            args: args\n          }));\n        }\n\n        try {\n          curr = curr.caller;\n        } catch (e) {\n          break;\n        }\n      }\n\n      return stack;\n    }\n  };\n});\n\n/* removed: var _$errorStackParser_10 = require('./lib/error-stack-parser'); */;\n\n/* removed: var _$stackGenerator_33 = require('stack-generator'); */;\n\n/* removed: var _$hasStack_19 = require('./lib/has-stack'); */;\n\n/* removed: var _$map_16 = require('./lib/es-utils/map'); */;\n\n/* removed: var _$reduce_17 = require('./lib/es-utils/reduce'); */;\n\n/* removed: var _$filter_12 = require('./lib/es-utils/filter'); */;\n\n/* removed: var _$assign_11 = require('./lib/es-utils/assign'); */;\n\n/* removed: var _$metadataDelegate_22 = require('./lib/metadata-delegate'); */;\n\n/* removed: var _$featureFlagDelegate_18 = require('./lib/feature-flag-delegate'); */;\n\n/* removed: var _$iserror_20 = require('./lib/iserror'); */;\n\nvar Event = /*#__PURE__*/function () {\n  function Event(errorClass, errorMessage, stacktrace, handledState, originalError) {\n    if (stacktrace === void 0) {\n      stacktrace = [];\n    }\n\n    if (handledState === void 0) {\n      handledState = defaultHandledState();\n    }\n\n    this.apiKey = undefined;\n    this.context = undefined;\n    this.groupingHash = undefined;\n    this.originalError = originalError;\n    this._handledState = handledState;\n    this.severity = this._handledState.severity;\n    this.unhandled = this._handledState.unhandled;\n    this.app = {};\n    this.device = {};\n    this.request = {};\n    this.breadcrumbs = [];\n    this.threads = [];\n    this._metadata = {};\n    this._features = [];\n    this._featuresIndex = {};\n    this._user = {};\n    this._session = undefined;\n    this.errors = [createBugsnagError(errorClass, errorMessage, Event.__type, stacktrace)]; // Flags.\n    // Note these are not initialised unless they are used\n    // to save unnecessary bytes in the browser bundle\n\n    /* this.attemptImmediateDelivery, default: true */\n  }\n\n  var _proto = Event.prototype;\n\n  _proto.addMetadata = function addMetadata(section, keyOrObj, maybeVal) {\n    return _$metadataDelegate_22.add(this._metadata, section, keyOrObj, maybeVal);\n  };\n\n  _proto.getMetadata = function getMetadata(section, key) {\n    return _$metadataDelegate_22.get(this._metadata, section, key);\n  };\n\n  _proto.clearMetadata = function clearMetadata(section, key) {\n    return _$metadataDelegate_22.clear(this._metadata, section, key);\n  };\n\n  _proto.addFeatureFlag = function addFeatureFlag(name, variant) {\n    if (variant === void 0) {\n      variant = null;\n    }\n\n    _$featureFlagDelegate_18.add(this._features, this._featuresIndex, name, variant);\n  };\n\n  _proto.addFeatureFlags = function addFeatureFlags(featureFlags) {\n    _$featureFlagDelegate_18.merge(this._features, featureFlags, this._featuresIndex);\n  };\n\n  _proto.getFeatureFlags = function getFeatureFlags() {\n    return _$featureFlagDelegate_18.toEventApi(this._features);\n  };\n\n  _proto.clearFeatureFlag = function clearFeatureFlag(name) {\n    _$featureFlagDelegate_18.clear(this._features, this._featuresIndex, name);\n  };\n\n  _proto.clearFeatureFlags = function clearFeatureFlags() {\n    this._features = [];\n    this._featuresIndex = {};\n  };\n\n  _proto.getUser = function getUser() {\n    return this._user;\n  };\n\n  _proto.setUser = function setUser(id, email, name) {\n    this._user = {\n      id: id,\n      email: email,\n      name: name\n    };\n  };\n\n  _proto.toJSON = function toJSON() {\n    return {\n      payloadVersion: '4',\n      exceptions: _$map_16(this.errors, function (er) {\n        return _$assign_11({}, er, {\n          message: er.errorMessage\n        });\n      }),\n      severity: this.severity,\n      unhandled: this._handledState.unhandled,\n      severityReason: this._handledState.severityReason,\n      app: this.app,\n      device: this.device,\n      request: this.request,\n      breadcrumbs: this.breadcrumbs,\n      context: this.context,\n      groupingHash: this.groupingHash,\n      metaData: this._metadata,\n      user: this._user,\n      session: this._session,\n      featureFlags: this.getFeatureFlags()\n    };\n  };\n\n  return Event;\n}(); // takes a stacktrace.js style stackframe (https://github.com/stacktracejs/stackframe)\n// and returns a Bugsnag compatible stackframe (https://docs.bugsnag.com/api/error-reporting/#json-payload)\n\n\nvar formatStackframe = function (frame) {\n  var f = {\n    file: frame.fileName,\n    method: normaliseFunctionName(frame.functionName),\n    lineNumber: frame.lineNumber,\n    columnNumber: frame.columnNumber,\n    code: undefined,\n    inProject: undefined\n  }; // Some instances result in no file:\n  // - calling notify() from chrome's terminal results in no file/method.\n  // - non-error exception thrown from global code in FF\n  // This adds one.\n\n  if (f.lineNumber > -1 && !f.file && !f.method) {\n    f.file = 'global code';\n  }\n\n  return f;\n};\n\nvar normaliseFunctionName = function (name) {\n  return /^global code$/i.test(name) ? 'global code' : name;\n};\n\nvar defaultHandledState = function () {\n  return {\n    unhandled: false,\n    severity: 'warning',\n    severityReason: {\n      type: 'handledException'\n    }\n  };\n};\n\nvar ensureString = function (str) {\n  return typeof str === 'string' ? str : '';\n};\n\nfunction createBugsnagError(errorClass, errorMessage, type, stacktrace) {\n  return {\n    errorClass: ensureString(errorClass),\n    errorMessage: ensureString(errorMessage),\n    type: type,\n    stacktrace: _$reduce_17(stacktrace, function (accum, frame) {\n      var f = formatStackframe(frame); // don't include a stackframe if none of its properties are defined\n\n      try {\n        if (JSON.stringify(f) === '{}') return accum;\n        return accum.concat(f);\n      } catch (e) {\n        return accum;\n      }\n    }, [])\n  };\n}\n\nfunction getCauseStack(error) {\n  if (error.cause) {\n    return [error].concat(getCauseStack(error.cause));\n  } else {\n    return [error];\n  }\n} // Helpers\n\n\nEvent.getStacktrace = function (error, errorFramesToSkip, backtraceFramesToSkip) {\n  if (_$hasStack_19(error)) return _$errorStackParser_10.parse(error).slice(errorFramesToSkip); // error wasn't provided or didn't have a stacktrace so try to walk the callstack\n\n  try {\n    return _$filter_12(_$stackGenerator_33.backtrace(), function (frame) {\n      return (frame.functionName || '').indexOf('StackGenerator$$') === -1;\n    }).slice(1 + backtraceFramesToSkip);\n  } catch (e) {\n    return [];\n  }\n};\n\nEvent.create = function (maybeError, tolerateNonErrors, handledState, component, errorFramesToSkip, logger) {\n  if (errorFramesToSkip === void 0) {\n    errorFramesToSkip = 0;\n  }\n\n  var _normaliseError = normaliseError(maybeError, tolerateNonErrors, component, logger),\n      error = _normaliseError[0],\n      internalFrames = _normaliseError[1];\n\n  var event;\n\n  try {\n    var stacktrace = Event.getStacktrace(error, // if an error was created/throw in the normaliseError() function, we need to\n    // tell the getStacktrace() function to skip the number of frames we know will\n    // be from our own functions. This is added to the number of frames deep we\n    // were told about\n    internalFrames > 0 ? 1 + internalFrames + errorFramesToSkip : 0, // if there's no stacktrace, the callstack may be walked to generated one.\n    // this is how many frames should be removed because they come from our library\n    1 + errorFramesToSkip);\n    event = new Event(error.name, error.message, stacktrace, handledState, maybeError);\n  } catch (e) {\n    event = new Event(error.name, error.message, [], handledState, maybeError);\n  }\n\n  if (error.name === 'InvalidError') {\n    event.addMetadata(\"\" + component, 'non-error parameter', makeSerialisable(maybeError));\n  }\n\n  if (error.cause) {\n    var _event$errors;\n\n    var causes = getCauseStack(error).slice(1);\n    var normalisedCauses = _$map_16(causes, function (cause) {\n      // Only get stacktrace for error causes that are a valid JS Error and already have a stack\n      var stacktrace = _$iserror_20(cause) && _$hasStack_19(cause) ? _$errorStackParser_10.parse(cause) : [];\n\n      var _normaliseError2 = normaliseError(cause, true, 'error cause'),\n          error = _normaliseError2[0];\n\n      if (error.name === 'InvalidError') event.addMetadata('error cause', makeSerialisable(cause));\n      return createBugsnagError(error.name, error.message, Event.__type, stacktrace);\n    });\n\n    (_event$errors = event.errors).push.apply(_event$errors, normalisedCauses);\n  }\n\n  return event;\n};\n\nvar makeSerialisable = function (err) {\n  if (err === null) return 'null';\n  if (err === undefined) return 'undefined';\n  return err;\n};\n\nvar normaliseError = function (maybeError, tolerateNonErrors, component, logger) {\n  var error;\n  var internalFrames = 0;\n\n  var createAndLogInputError = function (reason) {\n    var verb = component === 'error cause' ? 'was' : 'received';\n    if (logger) logger.warn(component + \" \" + verb + \" a non-error: \\\"\" + reason + \"\\\"\");\n    var err = new Error(component + \" \" + verb + \" a non-error. See \\\"\" + component + \"\\\" tab for more detail.\");\n    err.name = 'InvalidError';\n    return err;\n  }; // In some cases:\n  //\n  //  - the promise rejection handler (both in the browser and node)\n  //  - the node uncaughtException handler\n  //\n  // We are really limited in what we can do to get a stacktrace. So we use the\n  // tolerateNonErrors option to ensure that the resulting error communicates as\n  // such.\n\n\n  if (!tolerateNonErrors) {\n    if (_$iserror_20(maybeError)) {\n      error = maybeError;\n    } else {\n      error = createAndLogInputError(typeof maybeError);\n      internalFrames += 2;\n    }\n  } else {\n    switch (typeof maybeError) {\n      case 'string':\n      case 'number':\n      case 'boolean':\n        error = new Error(String(maybeError));\n        internalFrames += 1;\n        break;\n\n      case 'function':\n        error = createAndLogInputError('function');\n        internalFrames += 2;\n        break;\n\n      case 'object':\n        if (maybeError !== null && _$iserror_20(maybeError)) {\n          error = maybeError;\n        } else if (maybeError !== null && hasNecessaryFields(maybeError)) {\n          error = new Error(maybeError.message || maybeError.errorMessage);\n          error.name = maybeError.name || maybeError.errorClass;\n          internalFrames += 1;\n        } else {\n          error = createAndLogInputError(maybeError === null ? 'null' : 'unsupported object');\n          internalFrames += 2;\n        }\n\n        break;\n\n      default:\n        error = createAndLogInputError('nothing');\n        internalFrames += 2;\n    }\n  }\n\n  if (!_$hasStack_19(error)) {\n    // in IE10/11 a new Error() doesn't have a stacktrace until you throw it, so try that here\n    try {\n      throw error;\n    } catch (e) {\n      if (_$hasStack_19(e)) {\n        error = e; // if the error only got a stacktrace after we threw it here, we know it\n        // will only have one extra internal frame from this function, regardless\n        // of whether it went through createAndLogInputError() or not\n\n        internalFrames = 1;\n      }\n    }\n  }\n\n  return [error, internalFrames];\n}; // default value for stacktrace.type\n\n\nEvent.__type = 'browserjs';\n\nvar hasNecessaryFields = function (error) {\n  return (typeof error.name === 'string' || typeof error.errorClass === 'string') && (typeof error.message === 'string' || typeof error.errorMessage === 'string');\n};\n\nvar _$Event_6 = Event;\n\n// This is a heavily modified/simplified version of\n//   https://github.com/othiym23/async-some\n// with the logic flipped so that it is akin to the\n// synchronous \"every\" method instead of \"some\".\n// run the asynchronous test function (fn) over each item in the array (arr)\n// in series until:\n//   - fn(item, cb) => calls cb(null, false)\n//   - or the end of the array is reached\n// the callback (cb) will be passed (null, false) if any of the items in arr\n// caused fn to call back with false, otherwise it will be passed (null, true)\nvar _$asyncEvery_7 = function (arr, fn, cb) {\n  var index = 0;\n\n  var next = function () {\n    if (index >= arr.length) return cb(null, true);\n    fn(arr[index], function (err, result) {\n      if (err) return cb(err);\n      if (result === false) return cb(null, false);\n      index++;\n      next();\n    });\n  };\n\n  next();\n};\n\n/* removed: var _$asyncEvery_7 = require('./async-every'); */;\n\nvar _$callbackRunner_9 = function (callbacks, event, onCallbackError, cb) {\n  // This function is how we support different kinds of callback:\n  //  - synchronous - return value\n  //  - node-style async with callback - cb(err, value)\n  //  - promise/thenable - resolve(value)\n  // It normalises each of these into the lowest common denominator – a node-style callback\n  var runMaybeAsyncCallback = function (fn, cb) {\n    if (typeof fn !== 'function') return cb(null);\n\n    try {\n      // if function appears sync…\n      if (fn.length !== 2) {\n        var ret = fn(event); // check if it returned a \"thenable\" (promise)\n\n        if (ret && typeof ret.then === 'function') {\n          return ret.then( // resolve\n          function (val) {\n            return setTimeout(function () {\n              return cb(null, val);\n            });\n          }, // reject\n          function (err) {\n            setTimeout(function () {\n              onCallbackError(err);\n              return cb(null, true);\n            });\n          });\n        }\n\n        return cb(null, ret);\n      } // if function is async…\n\n\n      fn(event, function (err, result) {\n        if (err) {\n          onCallbackError(err);\n          return cb(null);\n        }\n\n        cb(null, result);\n      });\n    } catch (e) {\n      onCallbackError(e);\n      cb(null);\n    }\n  };\n\n  _$asyncEvery_7(callbacks, runMaybeAsyncCallback, cb);\n};\n\nvar _$syncCallbackRunner_23 = function (callbacks, callbackArg, callbackType, logger) {\n  var ignore = false;\n  var cbs = callbacks.slice();\n\n  while (!ignore) {\n    if (!cbs.length) break;\n\n    try {\n      ignore = cbs.pop()(callbackArg) === false;\n    } catch (e) {\n      logger.error(\"Error occurred in \" + callbackType + \" callback, continuing anyway\\u2026\");\n      logger.error(e);\n    }\n  }\n\n  return ignore;\n};\n\nvar _$pad_29 = function pad(num, size) {\n  var s = '000000000' + num;\n  return s.substr(s.length - size);\n};\n\n/* removed: var _$pad_29 = require('./pad.js'); */;\n\nvar env = typeof window === 'object' ? window : self;\nvar globalCount = 0;\n\nfor (var prop in env) {\n  if (Object.hasOwnProperty.call(env, prop)) globalCount++;\n}\n\nvar mimeTypesLength = navigator.mimeTypes ? navigator.mimeTypes.length : 0;\nvar clientId = _$pad_29((mimeTypesLength + navigator.userAgent.length).toString(36) + globalCount.toString(36), 4);\n\nvar _$fingerprint_28 = function fingerprint() {\n  return clientId;\n};\n\n/**\n * cuid.js\n * Collision-resistant UID generator for browsers and node.\n * Sequential for fast db lookups and recency sorting.\n * Safe for element IDs and server-side lookups.\n *\n * Extracted from CLCTR\n *\n * Copyright (c) Eric Elliott 2012\n * MIT License\n */\n/* removed: var _$fingerprint_28 = require('./lib/fingerprint.js'); */;\n\n/* removed: var _$pad_29 = require('./lib/pad.js'); */;\n\nvar c = 0,\n    blockSize = 4,\n    base = 36,\n    discreteValues = Math.pow(base, blockSize);\n\nfunction randomBlock() {\n  return _$pad_29((Math.random() * discreteValues << 0).toString(base), blockSize);\n}\n\nfunction safeCounter() {\n  c = c < discreteValues ? c : 0;\n  c++; // this is not subliminal\n\n  return c - 1;\n}\n\nfunction cuid() {\n  // Starting with a lowercase letter makes\n  // it HTML element ID friendly.\n  var letter = 'c',\n      // hard-coded allows for sequential access\n  // timestamp\n  // warning: this exposes the exact date and time\n  // that the uid was created.\n  timestamp = new Date().getTime().toString(base),\n      // Prevent same-machine collisions.\n  counter = _$pad_29(safeCounter().toString(base), blockSize),\n      // A few chars to generate distinct ids for different\n  // clients (so different computers are far less\n  // likely to generate the same id)\n  print = _$fingerprint_28(),\n      // Grab some more chars from Math.random()\n  random = randomBlock() + randomBlock();\n  return letter + timestamp + counter + print + random;\n}\n\ncuid.fingerprint = _$fingerprint_28;\nvar _$cuid_27 = cuid;\n\n/* removed: var _$cuid_27 = require('@bugsnag/cuid'); */;\n\nvar Session = /*#__PURE__*/function () {\n  function Session() {\n    this.id = _$cuid_27();\n    this.startedAt = new Date();\n    this._handled = 0;\n    this._unhandled = 0;\n    this._user = {};\n    this.app = {};\n    this.device = {};\n  }\n\n  var _proto = Session.prototype;\n\n  _proto.getUser = function getUser() {\n    return this._user;\n  };\n\n  _proto.setUser = function setUser(id, email, name) {\n    this._user = {\n      id: id,\n      email: email,\n      name: name\n    };\n  };\n\n  _proto.toJSON = function toJSON() {\n    return {\n      id: this.id,\n      startedAt: this.startedAt,\n      events: {\n        handled: this._handled,\n        unhandled: this._unhandled\n      }\n    };\n  };\n\n  _proto._track = function _track(event) {\n    this[event._handledState.unhandled ? '_unhandled' : '_handled'] += 1;\n  };\n\n  return Session;\n}();\n\nvar _$Session_35 = Session;\n\n/* removed: var _$config_5 = require('./config'); */;\n\n/* removed: var _$Event_6 = require('./event'); */;\n\n/* removed: var _$Breadcrumb_3 = require('./breadcrumb'); */;\n\n/* removed: var _$Session_35 = require('./session'); */;\n\n/* removed: var _$map_16 = require('./lib/es-utils/map'); */;\n\n/* removed: var _$includes_13 = require('./lib/es-utils/includes'); */;\n\n/* removed: var _$filter_12 = require('./lib/es-utils/filter'); */;\n\n/* removed: var _$reduce_17 = require('./lib/es-utils/reduce'); */;\n\n/* removed: var _$keys_15 = require('./lib/es-utils/keys'); */;\n\n/* removed: var _$assign_11 = require('./lib/es-utils/assign'); */;\n\n/* removed: var _$callbackRunner_9 = require('./lib/callback-runner'); */;\n\n/* removed: var _$metadataDelegate_22 = require('./lib/metadata-delegate'); */;\n\n/* removed: var _$syncCallbackRunner_23 = require('./lib/sync-callback-runner'); */;\n\n/* removed: var _$breadcrumbTypes_8 = require('./lib/breadcrumb-types'); */;\n\nvar __add_4 = _$featureFlagDelegate_18.add,\n    __clear_4 = _$featureFlagDelegate_18.clear,\n    __merge_4 = _$featureFlagDelegate_18.merge;\n\nvar noop = function () {};\n\nvar Client = /*#__PURE__*/function () {\n  function Client(configuration, schema, internalPlugins, notifier) {\n    var _this = this;\n\n    if (schema === void 0) {\n      schema = _$config_5.schema;\n    }\n\n    if (internalPlugins === void 0) {\n      internalPlugins = [];\n    }\n\n    // notifier id\n    this._notifier = notifier; // intialise opts and config\n\n    this._config = {};\n    this._schema = schema; // i/o\n\n    this._delivery = {\n      sendSession: noop,\n      sendEvent: noop\n    };\n    this._logger = {\n      debug: noop,\n      info: noop,\n      warn: noop,\n      error: noop\n    }; // plugins\n\n    this._plugins = {}; // state\n\n    this._breadcrumbs = [];\n    this._session = null;\n    this._metadata = {};\n    this._featuresIndex = {};\n    this._features = [];\n    this._context = undefined;\n    this._user = {}; // callbacks:\n    //  e: onError\n    //  s: onSession\n    //  sp: onSessionPayload\n    //  b: onBreadcrumb\n    // (note these names are minified by hand because object\n    // properties are not safe to minify automatically)\n\n    this._cbs = {\n      e: [],\n      s: [],\n      sp: [],\n      b: []\n    }; // expose internal constructors\n\n    this.Client = Client;\n    this.Event = _$Event_6;\n    this.Breadcrumb = _$Breadcrumb_3;\n    this.Session = _$Session_35;\n    this._config = this._configure(configuration, internalPlugins);\n    _$map_16(internalPlugins.concat(this._config.plugins), function (pl) {\n      if (pl) _this._loadPlugin(pl);\n    }); // when notify() is called we need to know how many frames are from our own source\n    // this inital value is 1 not 0 because we wrap notify() to ensure it is always\n    // bound to have the client as its `this` value – see below.\n\n    this._depth = 1;\n    var self = this;\n    var notify = this.notify;\n\n    this.notify = function () {\n      return notify.apply(self, arguments);\n    };\n  }\n\n  var _proto = Client.prototype;\n\n  _proto.addMetadata = function addMetadata(section, keyOrObj, maybeVal) {\n    return _$metadataDelegate_22.add(this._metadata, section, keyOrObj, maybeVal);\n  };\n\n  _proto.getMetadata = function getMetadata(section, key) {\n    return _$metadataDelegate_22.get(this._metadata, section, key);\n  };\n\n  _proto.clearMetadata = function clearMetadata(section, key) {\n    return _$metadataDelegate_22.clear(this._metadata, section, key);\n  };\n\n  _proto.addFeatureFlag = function addFeatureFlag(name, variant) {\n    if (variant === void 0) {\n      variant = null;\n    }\n\n    __add_4(this._features, this._featuresIndex, name, variant);\n  };\n\n  _proto.addFeatureFlags = function addFeatureFlags(featureFlags) {\n    __merge_4(this._features, featureFlags, this._featuresIndex);\n  };\n\n  _proto.clearFeatureFlag = function clearFeatureFlag(name) {\n    __clear_4(this._features, this._featuresIndex, name);\n  };\n\n  _proto.clearFeatureFlags = function clearFeatureFlags() {\n    this._features = [];\n    this._featuresIndex = {};\n  };\n\n  _proto.getContext = function getContext() {\n    return this._context;\n  };\n\n  _proto.setContext = function setContext(c) {\n    this._context = c;\n  };\n\n  _proto._configure = function _configure(opts, internalPlugins) {\n    var schema = _$reduce_17(internalPlugins, function (schema, plugin) {\n      if (plugin && plugin.configSchema) return _$assign_11({}, schema, plugin.configSchema);\n      return schema;\n    }, this._schema); // accumulate configuration and error messages\n\n    var _reduce = _$reduce_17(_$keys_15(schema), function (accum, key) {\n      var defaultValue = schema[key].defaultValue(opts[key]);\n\n      if (opts[key] !== undefined) {\n        var valid = schema[key].validate(opts[key]);\n\n        if (!valid) {\n          accum.errors[key] = schema[key].message;\n          accum.config[key] = defaultValue;\n        } else {\n          if (schema[key].allowPartialObject) {\n            accum.config[key] = _$assign_11(defaultValue, opts[key]);\n          } else {\n            accum.config[key] = opts[key];\n          }\n        }\n      } else {\n        accum.config[key] = defaultValue;\n      }\n\n      return accum;\n    }, {\n      errors: {},\n      config: {}\n    }),\n        errors = _reduce.errors,\n        config = _reduce.config;\n\n    if (schema.apiKey) {\n      // missing api key is the only fatal error\n      if (!config.apiKey) throw new Error('No Bugsnag API Key set'); // warn about an apikey that is not of the expected format\n\n      if (!/^[0-9a-f]{32}$/i.test(config.apiKey)) errors.apiKey = 'should be a string of 32 hexadecimal characters';\n    } // update and elevate some options\n\n\n    this._metadata = _$assign_11({}, config.metadata);\n    __merge_4(this._features, config.featureFlags, this._featuresIndex);\n    this._user = _$assign_11({}, config.user);\n    this._context = config.context;\n    if (config.logger) this._logger = config.logger; // add callbacks\n\n    if (config.onError) this._cbs.e = this._cbs.e.concat(config.onError);\n    if (config.onBreadcrumb) this._cbs.b = this._cbs.b.concat(config.onBreadcrumb);\n    if (config.onSession) this._cbs.s = this._cbs.s.concat(config.onSession); // finally warn about any invalid config where we fell back to the default\n\n    if (_$keys_15(errors).length) {\n      this._logger.warn(generateConfigErrorMessage(errors, opts));\n    }\n\n    return config;\n  };\n\n  _proto.getUser = function getUser() {\n    return this._user;\n  };\n\n  _proto.setUser = function setUser(id, email, name) {\n    this._user = {\n      id: id,\n      email: email,\n      name: name\n    };\n  };\n\n  _proto._loadPlugin = function _loadPlugin(plugin) {\n    var result = plugin.load(this); // JS objects are not the safest way to store arbitrarily keyed values,\n    // so bookend the key with some characters that prevent tampering with\n    // stuff like __proto__ etc. (only store the result if the plugin had a\n    // name)\n\n    if (plugin.name) this._plugins[\"~\" + plugin.name + \"~\"] = result;\n    return this;\n  };\n\n  _proto.getPlugin = function getPlugin(name) {\n    return this._plugins[\"~\" + name + \"~\"];\n  };\n\n  _proto._setDelivery = function _setDelivery(d) {\n    this._delivery = d(this);\n  };\n\n  _proto.startSession = function startSession() {\n    var session = new _$Session_35();\n    session.app.releaseStage = this._config.releaseStage;\n    session.app.version = this._config.appVersion;\n    session.app.type = this._config.appType;\n    session._user = _$assign_11({}, this._user); // run onSession callbacks\n\n    var ignore = _$syncCallbackRunner_23(this._cbs.s, session, 'onSession', this._logger);\n\n    if (ignore) {\n      this._logger.debug('Session not started due to onSession callback');\n\n      return this;\n    }\n\n    return this._sessionDelegate.startSession(this, session);\n  };\n\n  _proto.addOnError = function addOnError(fn, front) {\n    if (front === void 0) {\n      front = false;\n    }\n\n    this._cbs.e[front ? 'unshift' : 'push'](fn);\n  };\n\n  _proto.removeOnError = function removeOnError(fn) {\n    this._cbs.e = _$filter_12(this._cbs.e, function (f) {\n      return f !== fn;\n    });\n  };\n\n  _proto._addOnSessionPayload = function _addOnSessionPayload(fn) {\n    this._cbs.sp.push(fn);\n  };\n\n  _proto.addOnSession = function addOnSession(fn) {\n    this._cbs.s.push(fn);\n  };\n\n  _proto.removeOnSession = function removeOnSession(fn) {\n    this._cbs.s = _$filter_12(this._cbs.s, function (f) {\n      return f !== fn;\n    });\n  };\n\n  _proto.addOnBreadcrumb = function addOnBreadcrumb(fn, front) {\n    if (front === void 0) {\n      front = false;\n    }\n\n    this._cbs.b[front ? 'unshift' : 'push'](fn);\n  };\n\n  _proto.removeOnBreadcrumb = function removeOnBreadcrumb(fn) {\n    this._cbs.b = _$filter_12(this._cbs.b, function (f) {\n      return f !== fn;\n    });\n  };\n\n  _proto.pauseSession = function pauseSession() {\n    return this._sessionDelegate.pauseSession(this);\n  };\n\n  _proto.resumeSession = function resumeSession() {\n    return this._sessionDelegate.resumeSession(this);\n  };\n\n  _proto.leaveBreadcrumb = function leaveBreadcrumb(message, metadata, type) {\n    // coerce bad values so that the defaults get set\n    message = typeof message === 'string' ? message : '';\n    type = typeof type === 'string' && _$includes_13(_$breadcrumbTypes_8, type) ? type : 'manual';\n    metadata = typeof metadata === 'object' && metadata !== null ? metadata : {}; // if no message, discard\n\n    if (!message) return;\n    var crumb = new _$Breadcrumb_3(message, metadata, type); // run onBreadcrumb callbacks\n\n    var ignore = _$syncCallbackRunner_23(this._cbs.b, crumb, 'onBreadcrumb', this._logger);\n\n    if (ignore) {\n      this._logger.debug('Breadcrumb not attached due to onBreadcrumb callback');\n\n      return;\n    } // push the valid crumb onto the queue and maintain the length\n\n\n    this._breadcrumbs.push(crumb);\n\n    if (this._breadcrumbs.length > this._config.maxBreadcrumbs) {\n      this._breadcrumbs = this._breadcrumbs.slice(this._breadcrumbs.length - this._config.maxBreadcrumbs);\n    }\n  };\n\n  _proto._isBreadcrumbTypeEnabled = function _isBreadcrumbTypeEnabled(type) {\n    var types = this._config.enabledBreadcrumbTypes;\n    return types === null || _$includes_13(types, type);\n  };\n\n  _proto.notify = function notify(maybeError, onError, postReportCallback) {\n    if (postReportCallback === void 0) {\n      postReportCallback = noop;\n    }\n\n    var event = _$Event_6.create(maybeError, true, undefined, 'notify()', this._depth + 1, this._logger);\n\n    this._notify(event, onError, postReportCallback);\n  };\n\n  _proto._notify = function _notify(event, onError, postReportCallback) {\n    var _this2 = this;\n\n    if (postReportCallback === void 0) {\n      postReportCallback = noop;\n    }\n\n    event.app = _$assign_11({}, event.app, {\n      releaseStage: this._config.releaseStage,\n      version: this._config.appVersion,\n      type: this._config.appType\n    });\n    event.context = event.context || this._context;\n    event._metadata = _$assign_11({}, event._metadata, this._metadata);\n    event._user = _$assign_11({}, event._user, this._user);\n    event.breadcrumbs = this._breadcrumbs.slice();\n    __merge_4(event._features, this._features, event._featuresIndex); // exit early if events should not be sent on the current releaseStage\n\n    if (this._config.enabledReleaseStages !== null && !_$includes_13(this._config.enabledReleaseStages, this._config.releaseStage)) {\n      this._logger.warn('Event not sent due to releaseStage/enabledReleaseStages configuration');\n\n      return postReportCallback(null, event);\n    }\n\n    var originalSeverity = event.severity;\n\n    var onCallbackError = function (err) {\n      // errors in callbacks are tolerated but we want to log them out\n      _this2._logger.error('Error occurred in onError callback, continuing anyway…');\n\n      _this2._logger.error(err);\n    };\n\n    var callbacks = [].concat(this._cbs.e).concat(onError);\n    _$callbackRunner_9(callbacks, event, onCallbackError, function (err, shouldSend) {\n      if (err) onCallbackError(err);\n\n      if (!shouldSend) {\n        _this2._logger.debug('Event not sent due to onError callback');\n\n        return postReportCallback(null, event);\n      }\n\n      if (_this2._isBreadcrumbTypeEnabled('error')) {\n        // only leave a crumb for the error if actually got sent\n        Client.prototype.leaveBreadcrumb.call(_this2, event.errors[0].errorClass, {\n          errorClass: event.errors[0].errorClass,\n          errorMessage: event.errors[0].errorMessage,\n          severity: event.severity\n        }, 'error');\n      }\n\n      if (originalSeverity !== event.severity) {\n        event._handledState.severityReason = {\n          type: 'userCallbackSetSeverity'\n        };\n      }\n\n      if (event.unhandled !== event._handledState.unhandled) {\n        event._handledState.severityReason.unhandledOverridden = true;\n        event._handledState.unhandled = event.unhandled;\n      }\n\n      if (_this2._session) {\n        _this2._session._track(event);\n\n        event._session = _this2._session;\n      }\n\n      _this2._delivery.sendEvent({\n        apiKey: event.apiKey || _this2._config.apiKey,\n        notifier: _this2._notifier,\n        events: [event]\n      }, function (err) {\n        return postReportCallback(err, event);\n      });\n    });\n  };\n\n  return Client;\n}();\n\nvar generateConfigErrorMessage = function (errors, rawInput) {\n  var er = new Error(\"Invalid configuration\\n\" + _$map_16(_$keys_15(errors), function (key) {\n    return \"  - \" + key + \" \" + errors[key] + \", got \" + stringify(rawInput[key]);\n  }).join('\\n\\n'));\n  return er;\n};\n\nvar stringify = function (val) {\n  switch (typeof val) {\n    case 'string':\n    case 'number':\n    case 'object':\n      return JSON.stringify(val);\n\n    default:\n      return String(val);\n  }\n};\n\nvar _$Client_4 = Client;\n\nvar _$jsonPayload_21 = {};\n/* removed: var _$safeJsonStringify_30 = require('@bugsnag/safe-json-stringify'); */;\n\nvar EVENT_REDACTION_PATHS = ['events.[].metaData', 'events.[].breadcrumbs.[].metaData', 'events.[].request'];\n\n_$jsonPayload_21.event = function (event, redactedKeys) {\n  var payload = _$safeJsonStringify_30(event, null, null, {\n    redactedPaths: EVENT_REDACTION_PATHS,\n    redactedKeys: redactedKeys\n  });\n\n  if (payload.length > 10e5) {\n    event.events[0]._metadata = {\n      notifier: \"WARNING!\\nSerialized payload was \" + payload.length / 10e5 + \"MB (limit = 1MB)\\nmetadata was removed\"\n    };\n    payload = _$safeJsonStringify_30(event, null, null, {\n      redactedPaths: EVENT_REDACTION_PATHS,\n      redactedKeys: redactedKeys\n    });\n  }\n\n  return payload;\n};\n\n_$jsonPayload_21.session = function (session, redactedKeys) {\n  var payload = _$safeJsonStringify_30(session, null, null);\n  return payload;\n};\n\nvar _$delivery_36 = {};\n/* removed: var _$jsonPayload_21 = require('@bugsnag/core/lib/json-payload'); */;\n\n_$delivery_36 = function (client, win) {\n  if (win === void 0) {\n    win = window;\n  }\n\n  return {\n    sendEvent: function (event, cb) {\n      if (cb === void 0) {\n        cb = function () {};\n      }\n\n      var url = getApiUrl(client._config, 'notify', '4', win);\n      var body = _$jsonPayload_21.event(event, client._config.redactedKeys);\n      var req = new win.XDomainRequest();\n\n      req.onload = function () {\n        cb(null);\n      };\n\n      req.onerror = function () {\n        var err = new Error('Event failed to send');\n\n        client._logger.error('Event failed to send…', err);\n\n        if (body.length > 10e5) {\n          client._logger.warn(\"Event oversized (\" + (body.length / 10e5).toFixed(2) + \" MB)\");\n        }\n\n        cb(err);\n      };\n\n      req.open('POST', url);\n      setTimeout(function () {\n        try {\n          req.send(body);\n        } catch (e) {\n          client._logger.error(e);\n\n          cb(e);\n        }\n      }, 0);\n    },\n    sendSession: function (session, cb) {\n      if (cb === void 0) {\n        cb = function () {};\n      }\n\n      var url = getApiUrl(client._config, 'sessions', '1', win);\n      var req = new win.XDomainRequest();\n\n      req.onload = function () {\n        cb(null);\n      };\n\n      req.open('POST', url);\n      setTimeout(function () {\n        try {\n          req.send(_$jsonPayload_21.session(session, client._config.redactedKeys));\n        } catch (e) {\n          client._logger.error(e);\n\n          cb(e);\n        }\n      }, 0);\n    }\n  };\n};\n\nvar getApiUrl = function (config, endpoint, version, win) {\n  // IE8 doesn't support Date.prototype.toISOstring(), but it does convert a date\n  // to an ISO string when you use JSON stringify. Simply parsing the result of\n  // JSON.stringify is smaller than using a toISOstring() polyfill.\n  var isoDate = JSON.parse(JSON.stringify(new Date()));\n  var url = matchPageProtocol(config.endpoints[endpoint], win.location.protocol);\n  return url + \"?apiKey=\" + encodeURIComponent(config.apiKey) + \"&payloadVersion=\" + version + \"&sentAt=\" + encodeURIComponent(isoDate);\n};\n\nvar matchPageProtocol = _$delivery_36._matchPageProtocol = function (endpoint, pageProtocol) {\n  return pageProtocol === 'http:' ? endpoint.replace(/^https:/, 'http:') : endpoint;\n};\n\n/* removed: var _$jsonPayload_21 = require('@bugsnag/core/lib/json-payload'); */;\n\nvar _$delivery_37 = function (client, win) {\n  if (win === void 0) {\n    win = window;\n  }\n\n  return {\n    sendEvent: function (event, cb) {\n      if (cb === void 0) {\n        cb = function () {};\n      }\n\n      try {\n        var url = client._config.endpoints.notify;\n        var req = new win.XMLHttpRequest();\n        var body = _$jsonPayload_21.event(event, client._config.redactedKeys);\n\n        req.onreadystatechange = function () {\n          if (req.readyState === win.XMLHttpRequest.DONE) {\n            var status = req.status;\n\n            if (status === 0 || status >= 400) {\n              var err = new Error(\"Request failed with status \" + status);\n\n              client._logger.error('Event failed to send…', err);\n\n              if (body.length > 10e5) {\n                client._logger.warn(\"Event oversized (\" + (body.length / 10e5).toFixed(2) + \" MB)\");\n              }\n\n              cb(err);\n            } else {\n              cb(null);\n            }\n          }\n        };\n\n        req.open('POST', url);\n        req.setRequestHeader('Content-Type', 'application/json');\n        req.setRequestHeader('Bugsnag-Api-Key', event.apiKey || client._config.apiKey);\n        req.setRequestHeader('Bugsnag-Payload-Version', '4');\n        req.setRequestHeader('Bugsnag-Sent-At', new Date().toISOString());\n        req.send(body);\n      } catch (e) {\n        client._logger.error(e);\n      }\n    },\n    sendSession: function (session, cb) {\n      if (cb === void 0) {\n        cb = function () {};\n      }\n\n      try {\n        var url = client._config.endpoints.sessions;\n        var req = new win.XMLHttpRequest();\n\n        req.onreadystatechange = function () {\n          if (req.readyState === win.XMLHttpRequest.DONE) {\n            var status = req.status;\n\n            if (status === 0 || status >= 400) {\n              var err = new Error(\"Request failed with status \" + status);\n\n              client._logger.error('Session failed to send…', err);\n\n              cb(err);\n            } else {\n              cb(null);\n            }\n          }\n        };\n\n        req.open('POST', url);\n        req.setRequestHeader('Content-Type', 'application/json');\n        req.setRequestHeader('Bugsnag-Api-Key', client._config.apiKey);\n        req.setRequestHeader('Bugsnag-Payload-Version', '1');\n        req.setRequestHeader('Bugsnag-Sent-At', new Date().toISOString());\n        req.send(_$jsonPayload_21.session(session, client._config.redactedKeys));\n      } catch (e) {\n        client._logger.error(e);\n      }\n    }\n  };\n};\n\nvar appStart = new Date();\n\nvar reset = function () {\n  appStart = new Date();\n};\n\nvar _$app_38 = {\n  name: 'appDuration',\n  load: function (client) {\n    client.addOnError(function (event) {\n      var now = new Date();\n      event.app.duration = now - appStart;\n    }, true);\n    return {\n      reset: reset\n    };\n  }\n};\n\n/*\n * Sets the default context to be the current URL\n */\nvar _$context_39 = function (win) {\n  if (win === void 0) {\n    win = window;\n  }\n\n  return {\n    load: function (client) {\n      client.addOnError(function (event) {\n        if (event.context !== undefined) return;\n        event.context = win.location.pathname;\n      }, true);\n    }\n  };\n};\n\nvar _$pad_43 = function pad(num, size) {\n  var s = '000000000' + num;\n  return s.substr(s.length - size);\n};\n\n/* removed: var _$pad_43 = require('./pad.js'); */;\n\nvar __env_42 = typeof window === 'object' ? window : self;\nvar __globalCount_42 = 0;\n\nfor (var __prop_42 in __env_42) {\n  if (Object.hasOwnProperty.call(__env_42, __prop_42)) __globalCount_42++;\n}\n\nvar __mimeTypesLength_42 = navigator.mimeTypes ? navigator.mimeTypes.length : 0;\nvar __clientId_42 = _$pad_43((__mimeTypesLength_42 + navigator.userAgent.length).toString(36) + __globalCount_42.toString(36), 4);\n\nvar _$fingerprint_42 = function fingerprint() {\n  return __clientId_42;\n};\n\n/**\n * cuid.js\n * Collision-resistant UID generator for browsers and node.\n * Sequential for fast db lookups and recency sorting.\n * Safe for element IDs and server-side lookups.\n *\n * Extracted from CLCTR\n *\n * Copyright (c) Eric Elliott 2012\n * MIT License\n */\n/* removed: var _$fingerprint_42 = require('./lib/fingerprint.js'); */;\n\n/* removed: var _$pad_43 = require('./lib/pad.js'); */;\n\nvar __c_41 = 0,\n    __blockSize_41 = 4,\n    __base_41 = 36,\n    __discreteValues_41 = Math.pow(__base_41, __blockSize_41);\n\nfunction __randomBlock_41() {\n  return _$pad_43((Math.random() * __discreteValues_41 << 0).toString(__base_41), __blockSize_41);\n}\n\nfunction __safeCounter_41() {\n  __c_41 = __c_41 < __discreteValues_41 ? __c_41 : 0;\n  __c_41++; // this is not subliminal\n\n  return __c_41 - 1;\n}\n\nfunction __cuid_41() {\n  // Starting with a lowercase letter makes\n  // it HTML element ID friendly.\n  var letter = 'c',\n      // hard-coded allows for sequential access\n  // timestamp\n  // warning: this exposes the exact date and time\n  // that the uid was created.\n  timestamp = new Date().getTime().toString(__base_41),\n      // Prevent same-machine collisions.\n  counter = _$pad_43(__safeCounter_41().toString(__base_41), __blockSize_41),\n      // A few chars to generate distinct ids for different\n  // clients (so different computers are far less\n  // likely to generate the same id)\n  print = _$fingerprint_42(),\n      // Grab some more chars from Math.random()\n  random = __randomBlock_41() + __randomBlock_41();\n  return letter + timestamp + counter + print + random;\n}\n\n__cuid_41.fingerprint = _$fingerprint_42;\nvar _$cuid_41 = __cuid_41;\n\n/* removed: var _$assign_11 = require('@bugsnag/core/lib/es-utils/assign'); */;\n\nvar BUGSNAG_ANONYMOUS_ID_KEY = 'bugsnag-anonymous-id';\n\nvar getDeviceId = function (win) {\n  try {\n    var storage = win.localStorage;\n    var id = storage.getItem(BUGSNAG_ANONYMOUS_ID_KEY); // If we get an ID, make sure it looks like a valid cuid. The length can\n    // fluctuate slightly, so some leeway is built in\n\n    if (id && /^c[a-z0-9]{20,32}$/.test(id)) {\n      return id;\n    }\n\n    /* removed: var _$cuid_41 = require('@bugsnag/cuid'); */;\n\n    id = _$cuid_41();\n    storage.setItem(BUGSNAG_ANONYMOUS_ID_KEY, id);\n    return id;\n  } catch (err) {// If localStorage is not available (e.g. because it's disabled) then give up\n  }\n};\n/*\n * Automatically detects browser device details\n */\n\n\nvar _$device_40 = function (nav, win) {\n  if (nav === void 0) {\n    nav = navigator;\n  }\n\n  if (win === void 0) {\n    win = window;\n  }\n\n  return {\n    load: function (client) {\n      var device = {\n        locale: nav.browserLanguage || nav.systemLanguage || nav.userLanguage || nav.language,\n        userAgent: nav.userAgent\n      };\n\n      if (win && win.screen && win.screen.orientation && win.screen.orientation.type) {\n        device.orientation = win.screen.orientation.type;\n      } else if (win && win.document) {\n        device.orientation = win.document.documentElement.clientWidth > win.document.documentElement.clientHeight ? 'landscape' : 'portrait';\n      }\n\n      if (client._config.generateAnonymousId) {\n        device.id = getDeviceId(win);\n      }\n\n      client.addOnSession(function (session) {\n        session.device = _$assign_11({}, session.device, device); // only set device id if collectUserIp is false\n\n        if (!client._config.collectUserIp) setDefaultUserId(session);\n      }); // add time just as the event is sent\n\n      client.addOnError(function (event) {\n        event.device = _$assign_11({}, event.device, device, {\n          time: new Date()\n        });\n        if (!client._config.collectUserIp) setDefaultUserId(event);\n      }, true);\n    },\n    configSchema: {\n      generateAnonymousId: {\n        validate: function (value) {\n          return value === true || value === false;\n        },\n        defaultValue: function () {\n          return true;\n        },\n        message: 'should be true|false'\n      }\n    }\n  };\n};\n\nvar setDefaultUserId = function (eventOrSession) {\n  // device id is also used to populate the user id field, if it's not already set\n  var user = eventOrSession.getUser();\n\n  if (!user || !user.id) {\n    eventOrSession.setUser(eventOrSession.device.id);\n  }\n};\n\n/* removed: var _$assign_11 = require('@bugsnag/core/lib/es-utils/assign'); */;\n/*\n * Sets the event request: { url } to be the current href\n */\n\n\nvar _$request_44 = function (win) {\n  if (win === void 0) {\n    win = window;\n  }\n\n  return {\n    load: function (client) {\n      client.addOnError(function (event) {\n        if (event.request && event.request.url) return;\n        event.request = _$assign_11({}, event.request, {\n          url: win.location.href\n        });\n      }, true);\n    }\n  };\n};\n\n/* removed: var _$includes_13 = require('@bugsnag/core/lib/es-utils/includes'); */;\n\nvar _$session_45 = {\n  load: function (client) {\n    client._sessionDelegate = sessionDelegate;\n  }\n};\nvar sessionDelegate = {\n  startSession: function (client, session) {\n    var sessionClient = client;\n    sessionClient._session = session;\n    sessionClient._pausedSession = null; // exit early if the current releaseStage is not enabled\n\n    if (sessionClient._config.enabledReleaseStages !== null && !_$includes_13(sessionClient._config.enabledReleaseStages, sessionClient._config.releaseStage)) {\n      sessionClient._logger.warn('Session not sent due to releaseStage/enabledReleaseStages configuration');\n\n      return sessionClient;\n    }\n\n    sessionClient._delivery.sendSession({\n      notifier: sessionClient._notifier,\n      device: session.device,\n      app: session.app,\n      sessions: [{\n        id: session.id,\n        startedAt: session.startedAt,\n        user: session._user\n      }]\n    });\n\n    return sessionClient;\n  },\n  resumeSession: function (client) {\n    // Do nothing if there's already an active session\n    if (client._session) {\n      return client;\n    } // If we have a paused session then make it the active session\n\n\n    if (client._pausedSession) {\n      client._session = client._pausedSession;\n      client._pausedSession = null;\n      return client;\n    } // Otherwise start a new session\n\n\n    return client.startSession();\n  },\n  pauseSession: function (client) {\n    client._pausedSession = client._session;\n    client._session = null;\n  }\n};\n\n/* removed: var _$assign_11 = require('@bugsnag/core/lib/es-utils/assign'); */;\n/*\n * Prevent collection of user IPs\n */\n\n\nvar _$clientIp_46 = {\n  load: function (client) {\n    if (client._config.collectUserIp) return;\n    client.addOnError(function (event) {\n      // If user.id is explicitly undefined, it will be missing from the payload. It needs\n      // removing so that the following line replaces it\n      if (event._user && typeof event._user.id === 'undefined') delete event._user.id;\n      event._user = _$assign_11({\n        id: '[REDACTED]'\n      }, event._user);\n      event.request = _$assign_11({\n        clientIp: '[REDACTED]'\n      }, event.request);\n    });\n  },\n  configSchema: {\n    collectUserIp: {\n      defaultValue: function () {\n        return true;\n      },\n      message: 'should be true|false',\n      validate: function (value) {\n        return value === true || value === false;\n      }\n    }\n  }\n};\n\nvar _$consoleBreadcrumbs_47 = {};\n/* removed: var _$map_16 = require('@bugsnag/core/lib/es-utils/map'); */;\n\n/* removed: var _$reduce_17 = require('@bugsnag/core/lib/es-utils/reduce'); */;\n\n/* removed: var _$filter_12 = require('@bugsnag/core/lib/es-utils/filter'); */;\n/*\n * Leaves breadcrumbs when console log methods are called\n */\n\n\n_$consoleBreadcrumbs_47.load = function (client) {\n  var isDev = /^(local-)?dev(elopment)?$/.test(client._config.releaseStage);\n  if (isDev || !client._isBreadcrumbTypeEnabled('log')) return;\n  _$map_16(CONSOLE_LOG_METHODS, function (method) {\n    var original = console[method];\n\n    console[method] = function () {\n      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n        args[_key] = arguments[_key];\n      }\n\n      client.leaveBreadcrumb('Console output', _$reduce_17(args, function (accum, arg, i) {\n        // do the best/simplest stringification of each argument\n        var stringified = '[Unknown value]'; // this may fail if the input is:\n        // - an object whose [[Prototype]] is null (no toString)\n        // - an object with a broken toString or @@toPrimitive implementation\n\n        try {\n          stringified = String(arg);\n        } catch (e) {} // if it stringifies to [object Object] attempt to JSON stringify\n\n\n        if (stringified === '[object Object]') {\n          // catch stringify errors and fallback to [object Object]\n          try {\n            stringified = JSON.stringify(arg);\n          } catch (e) {}\n        }\n\n        accum[\"[\" + i + \"]\"] = stringified;\n        return accum;\n      }, {\n        severity: method.indexOf('group') === 0 ? 'log' : method\n      }), 'log');\n      original.apply(console, args);\n    };\n\n    console[method]._restore = function () {\n      console[method] = original;\n    };\n  });\n};\n\nif (\"production\" !== 'production') {\n  _$consoleBreadcrumbs_47.destroy = function () {\n    return CONSOLE_LOG_METHODS.forEach(function (method) {\n      if (typeof console[method]._restore === 'function') console[method]._restore();\n    });\n  };\n}\n\nvar CONSOLE_LOG_METHODS = _$filter_12(['log', 'debug', 'info', 'warn', 'error'], function (method) {\n  return typeof console !== 'undefined' && typeof console[method] === 'function';\n});\n\n/* removed: var _$map_16 = require('@bugsnag/core/lib/es-utils/map'); */;\n\n/* removed: var _$reduce_17 = require('@bugsnag/core/lib/es-utils/reduce'); */;\n\n/* removed: var _$filter_12 = require('@bugsnag/core/lib/es-utils/filter'); */;\n\nvar MAX_LINE_LENGTH = 200;\nvar MAX_SCRIPT_LENGTH = 500000;\n\nvar _$inlineScriptContent_48 = function (doc, win) {\n  if (doc === void 0) {\n    doc = document;\n  }\n\n  if (win === void 0) {\n    win = window;\n  }\n\n  return {\n    load: function (client) {\n      if (!client._config.trackInlineScripts) return;\n      var originalLocation = win.location.href;\n      var html = ''; // in IE8-10 the 'interactive' state can fire too soon (before scripts have finished executing), so in those\n      // we wait for the 'complete' state before assuming that synchronous scripts are no longer executing\n\n      var isOldIe = !!doc.attachEvent;\n      var DOMContentLoaded = isOldIe ? doc.readyState === 'complete' : doc.readyState !== 'loading';\n\n      var getHtml = function () {\n        return doc.documentElement.outerHTML;\n      }; // get whatever HTML exists at this point in time\n\n\n      html = getHtml();\n      var prev = doc.onreadystatechange; // then update it when the DOM content has loaded\n\n      doc.onreadystatechange = function () {\n        // IE8 compatible alternative to document#DOMContentLoaded\n        if (doc.readyState === 'interactive') {\n          html = getHtml();\n          DOMContentLoaded = true;\n        }\n\n        try {\n          prev.apply(this, arguments);\n        } catch (e) {}\n      };\n\n      var _lastScript = null;\n\n      var updateLastScript = function (script) {\n        _lastScript = script;\n      };\n\n      var getCurrentScript = function () {\n        var script = doc.currentScript || _lastScript;\n\n        if (!script && !DOMContentLoaded) {\n          var scripts = doc.scripts || doc.getElementsByTagName('script');\n          script = scripts[scripts.length - 1];\n        }\n\n        return script;\n      };\n\n      var addSurroundingCode = function (lineNumber) {\n        // get whatever html has rendered at this point\n        if (!DOMContentLoaded || !html) html = getHtml(); // simulate the raw html\n\n        var htmlLines = ['<!-- DOC START -->'].concat(html.split('\\n'));\n        var zeroBasedLine = lineNumber - 1;\n        var start = Math.max(zeroBasedLine - 3, 0);\n        var end = Math.min(zeroBasedLine + 3, htmlLines.length);\n        return _$reduce_17(htmlLines.slice(start, end), function (accum, line, i) {\n          accum[start + 1 + i] = line.length <= MAX_LINE_LENGTH ? line : line.substr(0, MAX_LINE_LENGTH);\n          return accum;\n        }, {});\n      };\n\n      client.addOnError(function (event) {\n        // remove any of our own frames that may be part the stack this\n        // happens before the inline script check as it happens for all errors\n        event.errors[0].stacktrace = _$filter_12(event.errors[0].stacktrace, function (f) {\n          return !/__trace__$/.test(f.method);\n        });\n        var frame = event.errors[0].stacktrace[0]; // if frame.file exists and is not the original location of the page, this can't be an inline script\n\n        if (frame && frame.file && frame.file.replace(/#.*$/, '') !== originalLocation.replace(/#.*$/, '')) return; // grab the last script known to have run\n\n        var currentScript = getCurrentScript();\n\n        if (currentScript) {\n          var content = currentScript.innerHTML;\n          event.addMetadata('script', 'content', content.length <= MAX_SCRIPT_LENGTH ? content : content.substr(0, MAX_SCRIPT_LENGTH)); // only attempt to grab some surrounding code if we have a line number\n\n          if (frame && frame.lineNumber) {\n            frame.code = addSurroundingCode(frame.lineNumber);\n          }\n        }\n      }, true); // Proxy all the timer functions whose callback is their 0th argument.\n      // Keep a reference to the original setTimeout because we need it later\n\n      var _map = _$map_16(['setTimeout', 'setInterval', 'setImmediate', 'requestAnimationFrame'], function (fn) {\n        return __proxy(win, fn, function (original) {\n          return __traceOriginalScript(original, function (args) {\n            return {\n              get: function () {\n                return args[0];\n              },\n              replace: function (fn) {\n                args[0] = fn;\n              }\n            };\n          });\n        });\n      }),\n          _setTimeout = _map[0]; // Proxy all the host objects whose prototypes have an addEventListener function\n\n\n      _$map_16(['EventTarget', 'Window', 'Node', 'ApplicationCache', 'AudioTrackList', 'ChannelMergerNode', 'CryptoOperation', 'EventSource', 'FileReader', 'HTMLUnknownElement', 'IDBDatabase', 'IDBRequest', 'IDBTransaction', 'KeyOperation', 'MediaController', 'MessagePort', 'ModalWindow', 'Notification', 'SVGElementInstance', 'Screen', 'TextTrack', 'TextTrackCue', 'TextTrackList', 'WebSocket', 'WebSocketWorker', 'Worker', 'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'XMLHttpRequestUpload'], function (o) {\n        if (!win[o] || !win[o].prototype || !Object.prototype.hasOwnProperty.call(win[o].prototype, 'addEventListener')) return;\n\n        __proxy(win[o].prototype, 'addEventListener', function (original) {\n          return __traceOriginalScript(original, eventTargetCallbackAccessor);\n        });\n\n        __proxy(win[o].prototype, 'removeEventListener', function (original) {\n          return __traceOriginalScript(original, eventTargetCallbackAccessor, true);\n        });\n      });\n\n      function __traceOriginalScript(fn, callbackAccessor, alsoCallOriginal) {\n        if (alsoCallOriginal === void 0) {\n          alsoCallOriginal = false;\n        }\n\n        return function () {\n          // this is required for removeEventListener to remove anything added with\n          // addEventListener before the functions started being wrapped by Bugsnag\n          var args = [].slice.call(arguments);\n\n          try {\n            var cba = callbackAccessor(args);\n            var cb = cba.get();\n            if (alsoCallOriginal) fn.apply(this, args);\n            if (typeof cb !== 'function') return fn.apply(this, args);\n\n            if (cb.__trace__) {\n              cba.replace(cb.__trace__);\n            } else {\n              var script = getCurrentScript(); // this function mustn't be annonymous due to a bug in the stack\n              // generation logic, meaning it gets tripped up\n              // see: https://github.com/stacktracejs/stack-generator/issues/6\n\n              cb.__trace__ = function __trace__() {\n                // set the script that called this function\n                updateLastScript(script); // immediately unset the currentScript synchronously below, however\n                // if this cb throws an error the line after will not get run so schedule\n                // an almost-immediate aysnc update too\n\n                _setTimeout(function () {\n                  updateLastScript(null);\n                }, 0);\n\n                var ret = cb.apply(this, arguments);\n                updateLastScript(null);\n                return ret;\n              };\n\n              cb.__trace__.__trace__ = cb.__trace__;\n              cba.replace(cb.__trace__);\n            }\n          } catch (e) {// swallow these errors on Selenium:\n            // Permission denied to access property '__trace__'\n            // WebDriverException: Message: Permission denied to access property \"handleEvent\"\n          } // IE8 doesn't let you call .apply() on setTimeout/setInterval\n\n\n          if (fn.apply) return fn.apply(this, args);\n\n          switch (args.length) {\n            case 1:\n              return fn(args[0]);\n\n            case 2:\n              return fn(args[0], args[1]);\n\n            default:\n              return fn();\n          }\n        };\n      }\n    },\n    configSchema: {\n      trackInlineScripts: {\n        validate: function (value) {\n          return value === true || value === false;\n        },\n        defaultValue: function () {\n          return true;\n        },\n        message: 'should be true|false'\n      }\n    }\n  };\n};\n\nfunction __proxy(host, name, replacer) {\n  var original = host[name];\n  if (!original) return original;\n  var replacement = replacer(original);\n  host[name] = replacement;\n  return original;\n}\n\nfunction eventTargetCallbackAccessor(args) {\n  var isEventHandlerObj = !!args[1] && typeof args[1].handleEvent === 'function';\n  return {\n    get: function () {\n      return isEventHandlerObj ? args[1].handleEvent : args[1];\n    },\n    replace: function (fn) {\n      if (isEventHandlerObj) {\n        args[1].handleEvent = fn;\n      } else {\n        args[1] = fn;\n      }\n    }\n  };\n}\n\n/*\n * Leaves breadcrumbs when the user interacts with the DOM\n */\nvar _$interactionBreadcrumbs_49 = function (win) {\n  if (win === void 0) {\n    win = window;\n  }\n\n  return {\n    load: function (client) {\n      if (!('addEventListener' in win)) return;\n      if (!client._isBreadcrumbTypeEnabled('user')) return;\n      win.addEventListener('click', function (event) {\n        var targetText, targetSelector;\n\n        try {\n          targetText = getNodeText(event.target);\n          targetSelector = getNodeSelector(event.target, win);\n        } catch (e) {\n          targetText = '[hidden]';\n          targetSelector = '[hidden]';\n\n          client._logger.error('Cross domain error when tracking click event. See docs: https://tinyurl.com/yy3rn63z');\n        }\n\n        client.leaveBreadcrumb('UI click', {\n          targetText: targetText,\n          targetSelector: targetSelector\n        }, 'user');\n      }, true);\n    }\n  };\n};\n\nvar trimStart = /^\\s+/;\nvar trimEnd = /(^|[^\\s])\\s+$/;\n\nfunction getNodeText(el) {\n  var text = el.textContent || el.innerText || '';\n\n  if (!text && (el.type === 'submit' || el.type === 'button')) {\n    text = el.value;\n  }\n\n  text = text.replace(trimStart, '').replace(trimEnd, '$1');\n\n  if (text.length > 140) {\n    return text.slice(0, 135) + '(...)';\n  }\n\n  return text;\n} // Create a label from tagname, id and css class of the element\n\n\nfunction getNodeSelector(el, win) {\n  var parts = [el.tagName];\n  if (el.id) parts.push('#' + el.id);\n  if (el.className && el.className.length) parts.push(\".\" + el.className.split(' ').join('.')); // Can't get much more advanced with the current browser\n\n  if (!win.document.querySelectorAll || !Array.prototype.indexOf) return parts.join('');\n\n  try {\n    if (win.document.querySelectorAll(parts.join('')).length === 1) return parts.join('');\n  } catch (e) {\n    // Sometimes the query selector can be invalid just return it as-is\n    return parts.join('');\n  } // try to get a more specific selector if this one matches more than one element\n\n\n  if (el.parentNode.childNodes.length > 1) {\n    var index = Array.prototype.indexOf.call(el.parentNode.childNodes, el) + 1;\n    parts.push(\":nth-child(\" + index + \")\");\n  }\n\n  if (win.document.querySelectorAll(parts.join('')).length === 1) return parts.join(''); // try prepending the parent node selector\n\n  if (el.parentNode) return getNodeSelector(el.parentNode, win) + \" > \" + parts.join('');\n  return parts.join('');\n}\n\nvar _$navigationBreadcrumbs_50 = {};\n/*\n* Leaves breadcrumbs when navigation methods are called or events are emitted\n*/\n_$navigationBreadcrumbs_50 = function (win) {\n  if (win === void 0) {\n    win = window;\n  }\n\n  var plugin = {\n    load: function (client) {\n      if (!('addEventListener' in win)) return;\n      if (!client._isBreadcrumbTypeEnabled('navigation')) return; // returns a function that will drop a breadcrumb with a given name\n\n      var drop = function (name) {\n        return function () {\n          return client.leaveBreadcrumb(name, {}, 'navigation');\n        };\n      }; // simple drops – just names, no meta\n\n\n      win.addEventListener('pagehide', drop('Page hidden'), true);\n      win.addEventListener('pageshow', drop('Page shown'), true);\n      win.addEventListener('load', drop('Page loaded'), true);\n      win.document.addEventListener('DOMContentLoaded', drop('DOMContentLoaded'), true); // some browsers like to emit popstate when the page loads, so only add the popstate listener after that\n\n      win.addEventListener('load', function () {\n        return win.addEventListener('popstate', drop('Navigated back'), true);\n      }); // hashchange has some metadata that we care about\n\n      win.addEventListener('hashchange', function (event) {\n        var metadata = event.oldURL ? {\n          from: relativeLocation(event.oldURL, win),\n          to: relativeLocation(event.newURL, win),\n          state: getCurrentState(win)\n        } : {\n          to: relativeLocation(win.location.href, win)\n        };\n        client.leaveBreadcrumb('Hash changed', metadata, 'navigation');\n      }, true); // the only way to know about replaceState/pushState is to wrap them… >_<\n\n      if (win.history.replaceState) wrapHistoryFn(client, win.history, 'replaceState', win);\n      if (win.history.pushState) wrapHistoryFn(client, win.history, 'pushState', win);\n    }\n  };\n\n  if (\"production\" !== 'production') {\n    plugin.destroy = function (win) {\n      if (win === void 0) {\n        win = window;\n      }\n\n      win.history.replaceState._restore();\n\n      win.history.pushState._restore();\n    };\n  }\n\n  return plugin;\n};\n\nif (\"production\" !== 'production') {\n  _$navigationBreadcrumbs_50.destroy = function (win) {\n    if (win === void 0) {\n      win = window;\n    }\n\n    win.history.replaceState._restore();\n\n    win.history.pushState._restore();\n  };\n} // takes a full url like http://foo.com:1234/pages/01.html?yes=no#section-2 and returns\n// just the path and hash parts, e.g. /pages/01.html?yes=no#section-2\n\n\nvar relativeLocation = function (url, win) {\n  var a = win.document.createElement('A');\n  a.href = url;\n  return \"\" + a.pathname + a.search + a.hash;\n};\n\nvar stateChangeToMetadata = function (win, state, title, url) {\n  var currentPath = relativeLocation(win.location.href, win);\n  return {\n    title: title,\n    state: state,\n    prevState: getCurrentState(win),\n    to: url || currentPath,\n    from: currentPath\n  };\n};\n\nvar wrapHistoryFn = function (client, target, fn, win) {\n  var orig = target[fn];\n\n  target[fn] = function (state, title, url) {\n    client.leaveBreadcrumb(\"History \" + fn, stateChangeToMetadata(win, state, title, url), 'navigation'); // if throttle plugin is in use, reset the event sent count\n\n    if (typeof client.resetEventCount === 'function') client.resetEventCount(); // if the client is operating in auto session-mode, a new route should trigger a new session\n\n    if (client._config.autoTrackSessions) client.startSession(); // Internet Explorer will convert `undefined` to a string when passed, causing an unintended redirect\n    // to '/undefined'. therefore we only pass the url if it's not undefined.\n\n    orig.apply(target, [state, title].concat(url !== undefined ? url : []));\n  };\n\n  if (\"production\" !== 'production') {\n    target[fn]._restore = function () {\n      target[fn] = orig;\n    };\n  }\n};\n\nvar getCurrentState = function (win) {\n  try {\n    return win.history.state;\n  } catch (e) {}\n};\n\nvar BREADCRUMB_TYPE = 'request';\n\n/* removed: var _$includes_13 = require('@bugsnag/core/lib/es-utils/includes'); */;\n/*\n * Leaves breadcrumbs when network requests occur\n */\n\n\nvar _$networkBreadcrumbs_51 = function (_ignoredUrls, win) {\n  if (_ignoredUrls === void 0) {\n    _ignoredUrls = [];\n  }\n\n  if (win === void 0) {\n    win = window;\n  }\n\n  var restoreFunctions = [];\n  var plugin = {\n    load: function (client) {\n      if (!client._isBreadcrumbTypeEnabled('request')) return;\n      var ignoredUrls = [client._config.endpoints.notify, client._config.endpoints.sessions].concat(_ignoredUrls);\n      monkeyPatchXMLHttpRequest();\n      monkeyPatchFetch(); // XMLHttpRequest monkey patch\n\n      function monkeyPatchXMLHttpRequest() {\n        if (!('addEventListener' in win.XMLHttpRequest.prototype)) return;\n        var nativeOpen = win.XMLHttpRequest.prototype.open; // override native open()\n\n        win.XMLHttpRequest.prototype.open = function open(method, url) {\n          var _this = this;\n\n          var requestSetupKey = false;\n\n          var error = function () {\n            return handleXHRError(method, url);\n          };\n\n          var load = function () {\n            return handleXHRLoad(method, url, _this.status);\n          }; // if we have already setup listeners, it means open() was called twice, we need to remove\n          // the listeners and recreate them\n\n\n          if (requestSetupKey) {\n            this.removeEventListener('load', load);\n            this.removeEventListener('error', error);\n          } // attach load event listener\n\n\n          this.addEventListener('load', load); // attach error event listener\n\n          this.addEventListener('error', error);\n          requestSetupKey = true;\n          nativeOpen.apply(this, arguments);\n        };\n\n        if (\"production\" !== 'production') {\n          restoreFunctions.push(function () {\n            win.XMLHttpRequest.prototype.open = nativeOpen;\n          });\n        }\n      }\n\n      function handleXHRLoad(method, url, status) {\n        if (url === undefined) {\n          client._logger.warn('The request URL is no longer present on this XMLHttpRequest. A breadcrumb cannot be left for this request.');\n\n          return;\n        } // an XMLHttpRequest's URL can be an object as long as its 'toString'\n        // returns a URL, e.g. a HTMLAnchorElement\n\n\n        if (typeof url === 'string' && _$includes_13(ignoredUrls, url.replace(/\\?.*$/, ''))) {\n          // don't leave a network breadcrumb from bugsnag notify calls\n          return;\n        }\n\n        var metadata = {\n          status: status,\n          request: method + \" \" + url\n        };\n\n        if (status >= 400) {\n          // contacted server but got an error response\n          client.leaveBreadcrumb('XMLHttpRequest failed', metadata, BREADCRUMB_TYPE);\n        } else {\n          client.leaveBreadcrumb('XMLHttpRequest succeeded', metadata, BREADCRUMB_TYPE);\n        }\n      }\n\n      function handleXHRError(method, url) {\n        if (url === undefined) {\n          client._logger.warn('The request URL is no longer present on this XMLHttpRequest. A breadcrumb cannot be left for this request.');\n\n          return;\n        }\n\n        if (typeof url === 'string' && _$includes_13(ignoredUrls, url.replace(/\\?.*$/, ''))) {\n          // don't leave a network breadcrumb from bugsnag notify calls\n          return;\n        } // failed to contact server\n\n\n        client.leaveBreadcrumb('XMLHttpRequest error', {\n          request: method + \" \" + url\n        }, BREADCRUMB_TYPE);\n      } // window.fetch monkey patch\n\n\n      function monkeyPatchFetch() {\n        // only patch it if it exists and if it is not a polyfill (patching a polyfilled\n        // fetch() results in duplicate breadcrumbs for the same request because the\n        // implementation uses XMLHttpRequest which is also patched)\n        if (!('fetch' in win) || win.fetch.polyfill) return;\n        var oldFetch = win.fetch;\n\n        win.fetch = function fetch() {\n          var _arguments = arguments;\n          var urlOrRequest = arguments[0];\n          var options = arguments[1];\n          var method;\n          var url = null;\n\n          if (urlOrRequest && typeof urlOrRequest === 'object') {\n            url = urlOrRequest.url;\n\n            if (options && 'method' in options) {\n              method = options.method;\n            } else if (urlOrRequest && 'method' in urlOrRequest) {\n              method = urlOrRequest.method;\n            }\n          } else {\n            url = urlOrRequest;\n\n            if (options && 'method' in options) {\n              method = options.method;\n            }\n          }\n\n          if (method === undefined) {\n            method = 'GET';\n          }\n\n          return new Promise(function (resolve, reject) {\n            // pass through to native fetch\n            oldFetch.apply(void 0, _arguments).then(function (response) {\n              handleFetchSuccess(response, method, url);\n              resolve(response);\n            })[\"catch\"](function (error) {\n              handleFetchError(method, url);\n              reject(error);\n            });\n          });\n        };\n\n        if (\"production\" !== 'production') {\n          restoreFunctions.push(function () {\n            win.fetch = oldFetch;\n          });\n        }\n      }\n\n      var handleFetchSuccess = function (response, method, url) {\n        var metadata = {\n          status: response.status,\n          request: method + \" \" + url\n        };\n\n        if (response.status >= 400) {\n          // when the request comes back with a 4xx or 5xx status it does not reject the fetch promise,\n          client.leaveBreadcrumb('fetch() failed', metadata, BREADCRUMB_TYPE);\n        } else {\n          client.leaveBreadcrumb('fetch() succeeded', metadata, BREADCRUMB_TYPE);\n        }\n      };\n\n      var handleFetchError = function (method, url) {\n        client.leaveBreadcrumb('fetch() error', {\n          request: method + \" \" + url\n        }, BREADCRUMB_TYPE);\n      };\n    }\n  };\n\n  if (\"production\" !== 'production') {\n    plugin.destroy = function () {\n      restoreFunctions.forEach(function (fn) {\n        return fn();\n      });\n      restoreFunctions = [];\n    };\n  }\n\n  return plugin;\n};\n\n/* removed: var _$intRange_24 = require('@bugsnag/core/lib/validators/int-range'); */;\n/*\n * Throttles and dedupes events\n */\n\n\nvar _$throttle_52 = {\n  load: function (client) {\n    // track sent events for each init of the plugin\n    var n = 0; // add onError hook\n\n    client.addOnError(function (event) {\n      // have max events been sent already?\n      if (n >= client._config.maxEvents) {\n        client._logger.warn(\"Cancelling event send due to maxEvents per session limit of \" + client._config.maxEvents + \" being reached\");\n\n        return false;\n      }\n\n      n++;\n    });\n\n    client.resetEventCount = function () {\n      n = 0;\n    };\n  },\n  configSchema: {\n    maxEvents: {\n      defaultValue: function () {\n        return 10;\n      },\n      message: 'should be a positive integer ≤100',\n      validate: function (val) {\n        return _$intRange_24(1, 100)(val);\n      }\n    }\n  }\n};\n\nvar _$stripQueryString_53 = {};\n/*\n * Remove query strings (and fragments) from stacktraces\n */\n/* removed: var _$map_16 = require('@bugsnag/core/lib/es-utils/map'); */;\n\n/* removed: var _$reduce_17 = require('@bugsnag/core/lib/es-utils/reduce'); */;\n\n_$stripQueryString_53 = {\n  load: function (client) {\n    client.addOnError(function (event) {\n      var allFrames = _$reduce_17(event.errors, function (accum, er) {\n        return accum.concat(er.stacktrace);\n      }, []);\n      _$map_16(allFrames, function (frame) {\n        frame.file = strip(frame.file);\n      });\n    });\n  }\n};\n\nvar strip = _$stripQueryString_53._strip = function (str) {\n  return typeof str === 'string' ? str.replace(/\\?.*$/, '').replace(/#.*$/, '') : str;\n};\n\n/*\n * Automatically notifies Bugsnag when window.onerror is called\n */\nvar _$onerror_54 = function (win, component) {\n  if (win === void 0) {\n    win = window;\n  }\n\n  if (component === void 0) {\n    component = 'window onerror';\n  }\n\n  return {\n    load: function (client) {\n      if (!client._config.autoDetectErrors) return;\n      if (!client._config.enabledErrorTypes.unhandledExceptions) return;\n\n      function onerror(messageOrEvent, url, lineNo, charNo, error) {\n        // Ignore errors with no info due to CORS settings\n        if (lineNo === 0 && /Script error\\.?/.test(messageOrEvent)) {\n          client._logger.warn('Ignoring cross-domain or eval script error. See docs: https://tinyurl.com/yy3rn63z');\n        } else {\n          // any error sent to window.onerror is unhandled and has severity=error\n          var handledState = {\n            severity: 'error',\n            unhandled: true,\n            severityReason: {\n              type: 'unhandledException'\n            }\n          };\n          var event; // window.onerror can be called in a number of ways. This big if-else is how we\n          // figure out which arguments were supplied, and what kind of values it received.\n\n          if (error) {\n            // if the last parameter (error) was supplied, this is a modern browser's\n            // way of saying \"this value was thrown and not caught\"\n            event = client.Event.create(error, true, handledState, component, 1);\n            decorateStack(event.errors[0].stacktrace, url, lineNo, charNo);\n          } else if ( // This complex case detects \"error\" events that are typically synthesised\n          // by jquery's trigger method (although can be created in other ways). In\n          // order to detect this:\n          // - the first argument (message) must exist and be an object (most likely it's a jQuery event)\n          // - the second argument (url) must either not exist or be something other than a string (if it\n          //    exists and is not a string, it'll be the extraParameters argument from jQuery's trigger()\n          //    function)\n          // - the third, fourth and fifth arguments must not exist (lineNo, charNo and error)\n          typeof messageOrEvent === 'object' && messageOrEvent !== null && (!url || typeof url !== 'string') && !lineNo && !charNo && !error) {\n            // The jQuery event may have a \"type\" property, if so use it as part of the error message\n            var name = messageOrEvent.type ? \"Event: \" + messageOrEvent.type : 'Error'; // attempt to find a message from one of the conventional properties, but\n            // default to empty string (the event will fill it with a placeholder)\n\n            var message = messageOrEvent.message || messageOrEvent.detail || '';\n            event = client.Event.create({\n              name: name,\n              message: message\n            }, true, handledState, component, 1); // provide the original thing onerror received – not our error-like object we passed to _notify\n\n            event.originalError = messageOrEvent; // include the raw input as metadata – it might contain more info than we extracted\n\n            event.addMetadata(component, {\n              event: messageOrEvent,\n              extraParameters: url\n            });\n          } else {\n            // Lastly, if there was no \"error\" parameter this event was probably from an old\n            // browser that doesn't support that. Instead we need to generate a stacktrace.\n            event = client.Event.create(messageOrEvent, true, handledState, component, 1);\n            decorateStack(event.errors[0].stacktrace, url, lineNo, charNo);\n          }\n\n          client._notify(event);\n        }\n\n        if (typeof prevOnError === 'function') prevOnError.apply(this, arguments);\n      }\n\n      var prevOnError = win.onerror;\n      win.onerror = onerror;\n    }\n  };\n}; // Sometimes the stacktrace has less information than was passed to window.onerror.\n// This function will augment the first stackframe with any useful info that was\n// received as arguments to the onerror callback.\n\n\nvar decorateStack = function (stack, url, lineNo, charNo) {\n  if (!stack[0]) stack.push({});\n  var culprit = stack[0];\n  if (!culprit.file && typeof url === 'string') culprit.file = url;\n  if (!culprit.lineNumber && isActualNumber(lineNo)) culprit.lineNumber = lineNo;\n\n  if (!culprit.columnNumber) {\n    if (isActualNumber(charNo)) {\n      culprit.columnNumber = charNo;\n    } else if (window.event && isActualNumber(window.event.errorCharacter)) {\n      culprit.columnNumber = window.event.errorCharacter;\n    }\n  }\n};\n\nvar isActualNumber = function (n) {\n  return typeof n === 'number' && String.call(n) !== 'NaN';\n};\n\n/* removed: var _$map_16 = require('@bugsnag/core/lib/es-utils/map'); */;\n\n/* removed: var _$iserror_20 = require('@bugsnag/core/lib/iserror'); */;\n\nvar _listener;\n/*\n * Automatically notifies Bugsnag when window.onunhandledrejection is called\n */\n\n\nvar _$unhandledRejection_55 = function (win) {\n  if (win === void 0) {\n    win = window;\n  }\n\n  var plugin = {\n    load: function (client) {\n      if (!client._config.autoDetectErrors || !client._config.enabledErrorTypes.unhandledRejections) return;\n\n      var listener = function (evt) {\n        var error = evt.reason;\n        var isBluebird = false; // accessing properties on evt.detail can throw errors (see #394)\n\n        try {\n          if (evt.detail && evt.detail.reason) {\n            error = evt.detail.reason;\n            isBluebird = true;\n          }\n        } catch (e) {}\n\n        var event = client.Event.create(error, false, {\n          severity: 'error',\n          unhandled: true,\n          severityReason: {\n            type: 'unhandledPromiseRejection'\n          }\n        }, 'unhandledrejection handler', 1, client._logger);\n\n        if (isBluebird) {\n          _$map_16(event.errors[0].stacktrace, fixBluebirdStacktrace(error));\n        }\n\n        client._notify(event, function (event) {\n          if (_$iserror_20(event.originalError) && !event.originalError.stack) {\n            var _event$addMetadata;\n\n            event.addMetadata('unhandledRejection handler', (_event$addMetadata = {}, _event$addMetadata[Object.prototype.toString.call(event.originalError)] = {\n              name: event.originalError.name,\n              message: event.originalError.message,\n              code: event.originalError.code\n            }, _event$addMetadata));\n          }\n        });\n      };\n\n      if ('addEventListener' in win) {\n        win.addEventListener('unhandledrejection', listener);\n      } else {\n        win.onunhandledrejection = function (reason, promise) {\n          listener({\n            detail: {\n              reason: reason,\n              promise: promise\n            }\n          });\n        };\n      }\n\n      _listener = listener;\n    }\n  };\n\n  if (\"production\" !== 'production') {\n    plugin.destroy = function (win) {\n      if (win === void 0) {\n        win = window;\n      }\n\n      if (_listener) {\n        if ('addEventListener' in win) {\n          win.removeEventListener('unhandledrejection', _listener);\n        } else {\n          win.onunhandledrejection = null;\n        }\n      }\n\n      _listener = null;\n    };\n  }\n\n  return plugin;\n}; // The stack parser on bluebird stacks in FF get a suprious first frame:\n//\n// Error: derp\n//   b@http://localhost:5000/bluebird.html:22:24\n//   a@http://localhost:5000/bluebird.html:18:9\n//   @http://localhost:5000/bluebird.html:14:9\n//\n// results in\n//   […]\n//     0: Object { file: \"Error: derp\", method: undefined, lineNumber: undefined, … }\n//     1: Object { file: \"http://localhost:5000/bluebird.html\", method: \"b\", lineNumber: 22, … }\n//     2: Object { file: \"http://localhost:5000/bluebird.html\", method: \"a\", lineNumber: 18, … }\n//     3: Object { file: \"http://localhost:5000/bluebird.html\", lineNumber: 14, columnNumber: 9, … }\n//\n// so the following reduce/accumulator function removes such frames\n//\n// Bluebird pads method names with spaces so trim that too…\n// https://github.com/petkaantonov/bluebird/blob/b7f21399816d02f979fe434585334ce901dcaf44/src/debuggability.js#L568-L571\n\n\nvar fixBluebirdStacktrace = function (error) {\n  return function (frame) {\n    if (frame.file === error.toString()) return;\n\n    if (frame.method) {\n      frame.method = frame.method.replace(/^\\s+/, '');\n    }\n  };\n};\n\nvar _$notifier_2 = {};\nvar name = 'Bugsnag JavaScript';\nvar version = '7.20.0';\nvar url = 'https://github.com/bugsnag/bugsnag-js';\n\n/* removed: var _$Client_4 = require('@bugsnag/core/client'); */;\n\n/* removed: var _$Event_6 = require('@bugsnag/core/event'); */;\n\n/* removed: var _$Session_35 = require('@bugsnag/core/session'); */;\n\n/* removed: var _$Breadcrumb_3 = require('@bugsnag/core/breadcrumb'); */;\n\n/* removed: var _$map_16 = require('@bugsnag/core/lib/es-utils/map'); */;\n\n/* removed: var _$keys_15 = require('@bugsnag/core/lib/es-utils/keys'); */;\n\n/* removed: var _$assign_11 = require('@bugsnag/core/lib/es-utils/assign'); */; // extend the base config schema with some browser-specific options\n\n\nvar __schema_2 = _$assign_11({}, _$config_5.schema, _$config_1);\n\n/* removed: var _$onerror_54 = require('@bugsnag/plugin-window-onerror'); */;\n\n/* removed: var _$unhandledRejection_55 = require('@bugsnag/plugin-window-unhandled-rejection'); */;\n\n/* removed: var _$app_38 = require('@bugsnag/plugin-app-duration'); */;\n\n/* removed: var _$device_40 = require('@bugsnag/plugin-browser-device'); */;\n\n/* removed: var _$context_39 = require('@bugsnag/plugin-browser-context'); */;\n\n/* removed: var _$request_44 = require('@bugsnag/plugin-browser-request'); */;\n\n/* removed: var _$throttle_52 = require('@bugsnag/plugin-simple-throttle'); */;\n\n/* removed: var _$consoleBreadcrumbs_47 = require('@bugsnag/plugin-console-breadcrumbs'); */;\n\n/* removed: var _$networkBreadcrumbs_51 = require('@bugsnag/plugin-network-breadcrumbs'); */;\n\n/* removed: var _$navigationBreadcrumbs_50 = require('@bugsnag/plugin-navigation-breadcrumbs'); */;\n\n/* removed: var _$interactionBreadcrumbs_49 = require('@bugsnag/plugin-interaction-breadcrumbs'); */;\n\n/* removed: var _$inlineScriptContent_48 = require('@bugsnag/plugin-inline-script-content'); */;\n\n/* removed: var _$session_45 = require('@bugsnag/plugin-browser-session'); */;\n\n/* removed: var _$clientIp_46 = require('@bugsnag/plugin-client-ip'); */;\n\n/* removed: var _$stripQueryString_53 = require('@bugsnag/plugin-strip-query-string'); */; // delivery mechanisms\n\n\n/* removed: var _$delivery_36 = require('@bugsnag/delivery-x-domain-request'); */;\n\n/* removed: var _$delivery_37 = require('@bugsnag/delivery-xml-http-request'); */;\n\nvar Bugsnag = {\n  _client: null,\n  createClient: function (opts) {\n    // handle very simple use case where user supplies just the api key as a string\n    if (typeof opts === 'string') opts = {\n      apiKey: opts\n    };\n    if (!opts) opts = {};\n    var internalPlugins = [// add browser-specific plugins\n    _$app_38, _$device_40(), _$context_39(), _$request_44(), _$throttle_52, _$session_45, _$clientIp_46, _$stripQueryString_53, _$onerror_54(), _$unhandledRejection_55(), _$navigationBreadcrumbs_50(), _$interactionBreadcrumbs_49(), _$networkBreadcrumbs_51(), _$consoleBreadcrumbs_47, // this one added last to avoid wrapping functionality before bugsnag uses it\n    _$inlineScriptContent_48()]; // configure a client with user supplied options\n\n    var bugsnag = new _$Client_4(opts, __schema_2, internalPlugins, {\n      name: name,\n      version: version,\n      url: url\n    }); // set delivery based on browser capability (IE 8+9 have an XDomainRequest object)\n\n    bugsnag._setDelivery(window.XDomainRequest ? _$delivery_36 : _$delivery_37);\n\n    bugsnag._logger.debug('Loaded!');\n\n    bugsnag.leaveBreadcrumb('Bugsnag loaded', {}, 'state');\n    return bugsnag._config.autoTrackSessions ? bugsnag.startSession() : bugsnag;\n  },\n  start: function (opts) {\n    if (Bugsnag._client) {\n      Bugsnag._client._logger.warn('Bugsnag.start() was called more than once. Ignoring.');\n\n      return Bugsnag._client;\n    }\n\n    Bugsnag._client = Bugsnag.createClient(opts);\n    return Bugsnag._client;\n  },\n  isStarted: function () {\n    return Bugsnag._client != null;\n  }\n};\n_$map_16(['resetEventCount'].concat(_$keys_15(_$Client_4.prototype)), function (m) {\n  if (/^_/.test(m)) return;\n\n  Bugsnag[m] = function () {\n    if (!Bugsnag._client) return console.log(\"Bugsnag.\" + m + \"() was called before Bugsnag.start()\");\n    Bugsnag._client._depth += 1;\n\n    var ret = Bugsnag._client[m].apply(Bugsnag._client, arguments);\n\n    Bugsnag._client._depth -= 1;\n    return ret;\n  };\n});\n_$notifier_2 = Bugsnag;\n_$notifier_2.Client = _$Client_4;\n_$notifier_2.Event = _$Event_6;\n_$notifier_2.Session = _$Session_35;\n_$notifier_2.Breadcrumb = _$Breadcrumb_3; // Export a \"default\" property for compatibility with ESM imports\n\n_$notifier_2[\"default\"] = Bugsnag;\n\nreturn _$notifier_2;\n\n});\n//# sourceMappingURL=bugsnag.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants.  Some of these (@defines) can be overridden at compile-time.\r\n */\r\nconst CONSTANTS = {\r\n    /**\r\n     * @define {boolean} Whether this is the client Node.js SDK.\r\n     */\r\n    NODE_CLIENT: false,\r\n    /**\r\n     * @define {boolean} Whether this is the Admin Node.js SDK.\r\n     */\r\n    NODE_ADMIN: false,\r\n    /**\r\n     * Firebase SDK Version\r\n     */\r\n    SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n */\r\nconst assert = function (assertion, message) {\r\n    if (!assertion) {\r\n        throw assertionError(message);\r\n    }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n */\r\nconst assertionError = function (message) {\r\n    return new Error('Firebase Database (' +\r\n        CONSTANTS.SDK_VERSION +\r\n        ') INTERNAL ASSERT FAILED: ' +\r\n        message);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst stringToByteArray$1 = function (str) {\r\n    // TODO(user): Use native implementations if/when available\r\n    const out = [];\r\n    let p = 0;\r\n    for (let i = 0; i < str.length; i++) {\r\n        let c = str.charCodeAt(i);\r\n        if (c < 128) {\r\n            out[p++] = c;\r\n        }\r\n        else if (c < 2048) {\r\n            out[p++] = (c >> 6) | 192;\r\n            out[p++] = (c & 63) | 128;\r\n        }\r\n        else if ((c & 0xfc00) === 0xd800 &&\r\n            i + 1 < str.length &&\r\n            (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n            // Surrogate Pair\r\n            c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n            out[p++] = (c >> 18) | 240;\r\n            out[p++] = ((c >> 12) & 63) | 128;\r\n            out[p++] = ((c >> 6) & 63) | 128;\r\n            out[p++] = (c & 63) | 128;\r\n        }\r\n        else {\r\n            out[p++] = (c >> 12) | 224;\r\n            out[p++] = ((c >> 6) & 63) | 128;\r\n            out[p++] = (c & 63) | 128;\r\n        }\r\n    }\r\n    return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nconst byteArrayToString = function (bytes) {\r\n    // TODO(user): Use native implementations if/when available\r\n    const out = [];\r\n    let pos = 0, c = 0;\r\n    while (pos < bytes.length) {\r\n        const c1 = bytes[pos++];\r\n        if (c1 < 128) {\r\n            out[c++] = String.fromCharCode(c1);\r\n        }\r\n        else if (c1 > 191 && c1 < 224) {\r\n            const c2 = bytes[pos++];\r\n            out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n        }\r\n        else if (c1 > 239 && c1 < 365) {\r\n            // Surrogate Pair\r\n            const c2 = bytes[pos++];\r\n            const c3 = bytes[pos++];\r\n            const c4 = bytes[pos++];\r\n            const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n                0x10000;\r\n            out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n            out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n        }\r\n        else {\r\n            const c2 = bytes[pos++];\r\n            const c3 = bytes[pos++];\r\n            out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n        }\r\n    }\r\n    return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nconst base64 = {\r\n    /**\r\n     * Maps bytes to characters.\r\n     */\r\n    byteToCharMap_: null,\r\n    /**\r\n     * Maps characters to bytes.\r\n     */\r\n    charToByteMap_: null,\r\n    /**\r\n     * Maps bytes to websafe characters.\r\n     * @private\r\n     */\r\n    byteToCharMapWebSafe_: null,\r\n    /**\r\n     * Maps websafe characters to bytes.\r\n     * @private\r\n     */\r\n    charToByteMapWebSafe_: null,\r\n    /**\r\n     * Our default alphabet, shared between\r\n     * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n     */\r\n    ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n    /**\r\n     * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n     */\r\n    get ENCODED_VALS() {\r\n        return this.ENCODED_VALS_BASE + '+/=';\r\n    },\r\n    /**\r\n     * Our websafe alphabet.\r\n     */\r\n    get ENCODED_VALS_WEBSAFE() {\r\n        return this.ENCODED_VALS_BASE + '-_.';\r\n    },\r\n    /**\r\n     * Whether this browser supports the atob and btoa functions. This extension\r\n     * started at Mozilla but is now implemented by many browsers. We use the\r\n     * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n     * but still allowing the standard per-browser compilations.\r\n     *\r\n     */\r\n    HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n    /**\r\n     * Base64-encode an array of bytes.\r\n     *\r\n     * @param input An array of bytes (numbers with\r\n     *     value in [0, 255]) to encode.\r\n     * @param webSafe Boolean indicating we should use the\r\n     *     alternative alphabet.\r\n     * @return The base64 encoded string.\r\n     */\r\n    encodeByteArray(input, webSafe) {\r\n        if (!Array.isArray(input)) {\r\n            throw Error('encodeByteArray takes an array as a parameter');\r\n        }\r\n        this.init_();\r\n        const byteToCharMap = webSafe\r\n            ? this.byteToCharMapWebSafe_\r\n            : this.byteToCharMap_;\r\n        const output = [];\r\n        for (let i = 0; i < input.length; i += 3) {\r\n            const byte1 = input[i];\r\n            const haveByte2 = i + 1 < input.length;\r\n            const byte2 = haveByte2 ? input[i + 1] : 0;\r\n            const haveByte3 = i + 2 < input.length;\r\n            const byte3 = haveByte3 ? input[i + 2] : 0;\r\n            const outByte1 = byte1 >> 2;\r\n            const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n            let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n            let outByte4 = byte3 & 0x3f;\r\n            if (!haveByte3) {\r\n                outByte4 = 64;\r\n                if (!haveByte2) {\r\n                    outByte3 = 64;\r\n                }\r\n            }\r\n            output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n        }\r\n        return output.join('');\r\n    },\r\n    /**\r\n     * Base64-encode a string.\r\n     *\r\n     * @param input A string to encode.\r\n     * @param webSafe If true, we should use the\r\n     *     alternative alphabet.\r\n     * @return The base64 encoded string.\r\n     */\r\n    encodeString(input, webSafe) {\r\n        // Shortcut for Mozilla browsers that implement\r\n        // a native base64 encoder in the form of \"btoa/atob\"\r\n        if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n            return btoa(input);\r\n        }\r\n        return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n    },\r\n    /**\r\n     * Base64-decode a string.\r\n     *\r\n     * @param input to decode.\r\n     * @param webSafe True if we should use the\r\n     *     alternative alphabet.\r\n     * @return string representing the decoded value.\r\n     */\r\n    decodeString(input, webSafe) {\r\n        // Shortcut for Mozilla browsers that implement\r\n        // a native base64 encoder in the form of \"btoa/atob\"\r\n        if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n            return atob(input);\r\n        }\r\n        return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n    },\r\n    /**\r\n     * Base64-decode a string.\r\n     *\r\n     * In base-64 decoding, groups of four characters are converted into three\r\n     * bytes.  If the encoder did not apply padding, the input length may not\r\n     * be a multiple of 4.\r\n     *\r\n     * In this case, the last group will have fewer than 4 characters, and\r\n     * padding will be inferred.  If the group has one or two characters, it decodes\r\n     * to one byte.  If the group has three characters, it decodes to two bytes.\r\n     *\r\n     * @param input Input to decode.\r\n     * @param webSafe True if we should use the web-safe alphabet.\r\n     * @return bytes representing the decoded value.\r\n     */\r\n    decodeStringToByteArray(input, webSafe) {\r\n        this.init_();\r\n        const charToByteMap = webSafe\r\n            ? this.charToByteMapWebSafe_\r\n            : this.charToByteMap_;\r\n        const output = [];\r\n        for (let i = 0; i < input.length;) {\r\n            const byte1 = charToByteMap[input.charAt(i++)];\r\n            const haveByte2 = i < input.length;\r\n            const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n            ++i;\r\n            const haveByte3 = i < input.length;\r\n            const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n            ++i;\r\n            const haveByte4 = i < input.length;\r\n            const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n            ++i;\r\n            if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n                throw new DecodeBase64StringError();\r\n            }\r\n            const outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n            output.push(outByte1);\r\n            if (byte3 !== 64) {\r\n                const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n                output.push(outByte2);\r\n                if (byte4 !== 64) {\r\n                    const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n                    output.push(outByte3);\r\n                }\r\n            }\r\n        }\r\n        return output;\r\n    },\r\n    /**\r\n     * Lazy static initialization function. Called before\r\n     * accessing any of the static map variables.\r\n     * @private\r\n     */\r\n    init_() {\r\n        if (!this.byteToCharMap_) {\r\n            this.byteToCharMap_ = {};\r\n            this.charToByteMap_ = {};\r\n            this.byteToCharMapWebSafe_ = {};\r\n            this.charToByteMapWebSafe_ = {};\r\n            // We want quick mappings back and forth, so we precompute two maps.\r\n            for (let i = 0; i < this.ENCODED_VALS.length; i++) {\r\n                this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n                this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n                this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n                this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n                // Be forgiving when decoding and correctly decode both encodings.\r\n                if (i >= this.ENCODED_VALS_BASE.length) {\r\n                    this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n                    this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n                }\r\n            }\r\n        }\r\n    }\r\n};\r\n/**\r\n * An error encountered while decoding base64 string.\r\n */\r\nclass DecodeBase64StringError extends Error {\r\n    constructor() {\r\n        super(...arguments);\r\n        this.name = 'DecodeBase64StringError';\r\n    }\r\n}\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nconst base64Encode = function (str) {\r\n    const utf8Bytes = stringToByteArray$1(str);\r\n    return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nconst base64urlEncodeWithoutPadding = function (str) {\r\n    // Use base64url encoding and remove padding in the end (dot characters).\r\n    return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nconst base64Decode = function (str) {\r\n    try {\r\n        return base64.decodeString(str, true);\r\n    }\r\n    catch (e) {\r\n        console.error('base64Decode failed: ', e);\r\n    }\r\n    return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n    return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays).  Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n    if (!(source instanceof Object)) {\r\n        return source;\r\n    }\r\n    switch (source.constructor) {\r\n        case Date:\r\n            // Treat Dates like scalars; if the target date object had any child\r\n            // properties - they will be lost!\r\n            const dateValue = source;\r\n            return new Date(dateValue.getTime());\r\n        case Object:\r\n            if (target === undefined) {\r\n                target = {};\r\n            }\r\n            break;\r\n        case Array:\r\n            // Always copy the array source and overwrite the target.\r\n            target = [];\r\n            break;\r\n        default:\r\n            // Not a plain Object - treat it as a scalar.\r\n            return source;\r\n    }\r\n    for (const prop in source) {\r\n        // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n        if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n            continue;\r\n        }\r\n        target[prop] = deepExtend(target[prop], source[prop]);\r\n    }\r\n    return target;\r\n}\r\nfunction isValidKey(key) {\r\n    return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n * @public\r\n */\r\nfunction getGlobal() {\r\n    if (typeof self !== 'undefined') {\r\n        return self;\r\n    }\r\n    if (typeof window !== 'undefined') {\r\n        return window;\r\n    }\r\n    if (typeof global !== 'undefined') {\r\n        return global;\r\n    }\r\n    throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\r\n/**\r\n * Attempt to read defaults from a JSON string provided to\r\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\r\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\r\n * The dots are in parens because certain compilers (Vite?) cannot\r\n * handle seeing that variable in comments.\r\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\r\n */\r\nconst getDefaultsFromEnvVariable = () => {\r\n    if (typeof process === 'undefined' || typeof process.env === 'undefined') {\r\n        return;\r\n    }\r\n    const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\r\n    if (defaultsJsonString) {\r\n        return JSON.parse(defaultsJsonString);\r\n    }\r\n};\r\nconst getDefaultsFromCookie = () => {\r\n    if (typeof document === 'undefined') {\r\n        return;\r\n    }\r\n    let match;\r\n    try {\r\n        match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\r\n    }\r\n    catch (e) {\r\n        // Some environments such as Angular Universal SSR have a\r\n        // `document` object but error on accessing `document.cookie`.\r\n        return;\r\n    }\r\n    const decoded = match && base64Decode(match[1]);\r\n    return decoded && JSON.parse(decoded);\r\n};\r\n/**\r\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\r\n * (1) if such an object exists as a property of `globalThis`\r\n * (2) if such an object was provided on a shell environment variable\r\n * (3) if such an object exists in a cookie\r\n * @public\r\n */\r\nconst getDefaults = () => {\r\n    try {\r\n        return (getDefaultsFromGlobal() ||\r\n            getDefaultsFromEnvVariable() ||\r\n            getDefaultsFromCookie());\r\n    }\r\n    catch (e) {\r\n        /**\r\n         * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\r\n         * to any environment case we have not accounted for. Log to\r\n         * info instead of swallowing so we can find these unknown cases\r\n         * and add paths for them if needed.\r\n         */\r\n        console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\r\n        return;\r\n    }\r\n};\r\n/**\r\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };\r\n/**\r\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\r\n    const host = getDefaultEmulatorHost(productName);\r\n    if (!host) {\r\n        return undefined;\r\n    }\r\n    const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\r\n    if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\r\n        throw new Error(`Invalid host ${host} with no separate hostname and port!`);\r\n    }\r\n    // eslint-disable-next-line no-restricted-globals\r\n    const port = parseInt(host.substring(separatorIndex + 1), 10);\r\n    if (host[0] === '[') {\r\n        // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\r\n        return [host.substring(1, separatorIndex - 1), port];\r\n    }\r\n    else {\r\n        return [host.substring(0, separatorIndex), port];\r\n    }\r\n};\r\n/**\r\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\r\n * @public\r\n */\r\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\r\n/**\r\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\r\n * prefixed by \"_\")\r\n * @public\r\n */\r\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Deferred {\r\n    constructor() {\r\n        this.reject = () => { };\r\n        this.resolve = () => { };\r\n        this.promise = new Promise((resolve, reject) => {\r\n            this.resolve = resolve;\r\n            this.reject = reject;\r\n        });\r\n    }\r\n    /**\r\n     * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n     * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n     * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n     */\r\n    wrapCallback(callback) {\r\n        return (error, value) => {\r\n            if (error) {\r\n                this.reject(error);\r\n            }\r\n            else {\r\n                this.resolve(value);\r\n            }\r\n            if (typeof callback === 'function') {\r\n                // Attaching noop handler just in case developer wasn't expecting\r\n                // promises\r\n                this.promise.catch(() => { });\r\n                // Some of our callbacks don't expect a value and our own tests\r\n                // assert that the parameter length is 1\r\n                if (callback.length === 1) {\r\n                    callback(error);\r\n                }\r\n                else {\r\n                    callback(error, value);\r\n                }\r\n            }\r\n        };\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n    if (token.uid) {\r\n        throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n    }\r\n    // Unsecured JWTs use \"none\" as the algorithm.\r\n    const header = {\r\n        alg: 'none',\r\n        type: 'JWT'\r\n    };\r\n    const project = projectId || 'demo-project';\r\n    const iat = token.iat || 0;\r\n    const sub = token.sub || token.user_id;\r\n    if (!sub) {\r\n        throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n    }\r\n    const payload = Object.assign({ \r\n        // Set all required fields to decent defaults\r\n        iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\r\n            sign_in_provider: 'custom',\r\n            identities: {}\r\n        } }, token);\r\n    // Unsecured JWTs use the empty string as a signature.\r\n    const signature = '';\r\n    return [\r\n        base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n        base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n        signature\r\n    ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n    if (typeof navigator !== 'undefined' &&\r\n        typeof navigator['userAgent'] === 'string') {\r\n        return navigator['userAgent'];\r\n    }\r\n    else {\r\n        return '';\r\n    }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n    return (typeof window !== 'undefined' &&\r\n        // @ts-ignore Setting up an broadly applicable index signature for Window\r\n        // just to deal with this case would probably be a bad idea.\r\n        !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n        /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected or specified.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n    var _a;\r\n    const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;\r\n    if (forceEnvironment === 'node') {\r\n        return true;\r\n    }\r\n    else if (forceEnvironment === 'browser') {\r\n        return false;\r\n    }\r\n    try {\r\n        return (Object.prototype.toString.call(global.process) === '[object process]');\r\n    }\r\n    catch (e) {\r\n        return false;\r\n    }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n    return typeof self === 'object' && self.self === self;\r\n}\r\nfunction isBrowserExtension() {\r\n    const runtime = typeof chrome === 'object'\r\n        ? chrome.runtime\r\n        : typeof browser === 'object'\r\n            ? browser.runtime\r\n            : undefined;\r\n    return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n    return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n    return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n    const ua = getUA();\r\n    return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n    return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n    return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n    return (!isNode() &&\r\n        navigator.userAgent.includes('Safari') &&\r\n        !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n    try {\r\n        return typeof indexedDB === 'object';\r\n    }\r\n    catch (e) {\r\n        return false;\r\n    }\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n    return new Promise((resolve, reject) => {\r\n        try {\r\n            let preExist = true;\r\n            const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\r\n            const request = self.indexedDB.open(DB_CHECK_NAME);\r\n            request.onsuccess = () => {\r\n                request.result.close();\r\n                // delete database only when it doesn't pre-exist\r\n                if (!preExist) {\r\n                    self.indexedDB.deleteDatabase(DB_CHECK_NAME);\r\n                }\r\n                resolve(true);\r\n            };\r\n            request.onupgradeneeded = () => {\r\n                preExist = false;\r\n            };\r\n            request.onerror = () => {\r\n                var _a;\r\n                reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n            };\r\n        }\r\n        catch (error) {\r\n            reject(error);\r\n        }\r\n    });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n    if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\r\n        return false;\r\n    }\r\n    return true;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Standardized Firebase Error.\r\n *\r\n * Usage:\r\n *\r\n *   // Typescript string literals for type-safe codes\r\n *   type Err =\r\n *     'unknown' |\r\n *     'object-not-found'\r\n *     ;\r\n *\r\n *   // Closure enum for type-safe error codes\r\n *   // at-enum {string}\r\n *   var Err = {\r\n *     UNKNOWN: 'unknown',\r\n *     OBJECT_NOT_FOUND: 'object-not-found',\r\n *   }\r\n *\r\n *   let errors: Map<Err, string> = {\r\n *     'generic-error': \"Unknown error\",\r\n *     'file-not-found': \"Could not find file: {$file}\",\r\n *   };\r\n *\r\n *   // Type-safe function - must pass a valid error code as param.\r\n *   let error = new ErrorFactory<Err>('service', 'Service', errors);\r\n *\r\n *   ...\r\n *   throw error.create(Err.GENERIC);\r\n *   ...\r\n *   throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n *   ...\r\n *   // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n *   catch (e) {\r\n *     assert(e.message === \"Could not find file: foo.txt.\");\r\n *     if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n *       console.log(\"Could not read file: \" + e['file']);\r\n *     }\r\n *   }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n    constructor(\r\n    /** The error code for this error. */\r\n    code, message, \r\n    /** Custom data for this error. */\r\n    customData) {\r\n        super(message);\r\n        this.code = code;\r\n        this.customData = customData;\r\n        /** The custom name for all FirebaseErrors. */\r\n        this.name = ERROR_NAME;\r\n        // Fix For ES5\r\n        // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n        Object.setPrototypeOf(this, FirebaseError.prototype);\r\n        // Maintains proper stack trace for where our error was thrown.\r\n        // Only available on V8.\r\n        if (Error.captureStackTrace) {\r\n            Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n        }\r\n    }\r\n}\r\nclass ErrorFactory {\r\n    constructor(service, serviceName, errors) {\r\n        this.service = service;\r\n        this.serviceName = serviceName;\r\n        this.errors = errors;\r\n    }\r\n    create(code, ...data) {\r\n        const customData = data[0] || {};\r\n        const fullCode = `${this.service}/${code}`;\r\n        const template = this.errors[code];\r\n        const message = template ? replaceTemplate(template, customData) : 'Error';\r\n        // Service Name: Error message (service/code).\r\n        const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n        const error = new FirebaseError(fullCode, fullMessage, customData);\r\n        return error;\r\n    }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n    return template.replace(PATTERN, (_, key) => {\r\n        const value = data[key];\r\n        return value != null ? String(value) : `<${key}?>`;\r\n    });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n    return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n    return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n    let header = {}, claims = {}, data = {}, signature = '';\r\n    try {\r\n        const parts = token.split('.');\r\n        header = jsonEval(base64Decode(parts[0]) || '');\r\n        claims = jsonEval(base64Decode(parts[1]) || '');\r\n        signature = parts[2];\r\n        data = claims['d'] || {};\r\n        delete claims['d'];\r\n    }\r\n    catch (e) { }\r\n    return {\r\n        header,\r\n        claims,\r\n        data,\r\n        signature\r\n    };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n    const claims = decode(token).claims;\r\n    const now = Math.floor(new Date().getTime() / 1000);\r\n    let validSince = 0, validUntil = 0;\r\n    if (typeof claims === 'object') {\r\n        if (claims.hasOwnProperty('nbf')) {\r\n            validSince = claims['nbf'];\r\n        }\r\n        else if (claims.hasOwnProperty('iat')) {\r\n            validSince = claims['iat'];\r\n        }\r\n        if (claims.hasOwnProperty('exp')) {\r\n            validUntil = claims['exp'];\r\n        }\r\n        else {\r\n            // token will expire after 24h by default\r\n            validUntil = validSince + 86400;\r\n        }\r\n    }\r\n    return (!!now &&\r\n        !!validSince &&\r\n        !!validUntil &&\r\n        now >= validSince &&\r\n        now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n    const claims = decode(token).claims;\r\n    if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n        return claims['iat'];\r\n    }\r\n    return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n    const decoded = decode(token), claims = decoded.claims;\r\n    return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n    const claims = decode(token).claims;\r\n    return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n    return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n        return obj[key];\r\n    }\r\n    else {\r\n        return undefined;\r\n    }\r\n}\r\nfunction isEmpty(obj) {\r\n    for (const key in obj) {\r\n        if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n            return false;\r\n        }\r\n    }\r\n    return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n    const res = {};\r\n    for (const key in obj) {\r\n        if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n            res[key] = fn.call(contextObj, obj[key], key, obj);\r\n        }\r\n    }\r\n    return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n    if (a === b) {\r\n        return true;\r\n    }\r\n    const aKeys = Object.keys(a);\r\n    const bKeys = Object.keys(b);\r\n    for (const k of aKeys) {\r\n        if (!bKeys.includes(k)) {\r\n            return false;\r\n        }\r\n        const aProp = a[k];\r\n        const bProp = b[k];\r\n        if (isObject(aProp) && isObject(bProp)) {\r\n            if (!deepEqual(aProp, bProp)) {\r\n                return false;\r\n            }\r\n        }\r\n        else if (aProp !== bProp) {\r\n            return false;\r\n        }\r\n    }\r\n    for (const k of bKeys) {\r\n        if (!aKeys.includes(k)) {\r\n            return false;\r\n        }\r\n    }\r\n    return true;\r\n}\r\nfunction isObject(thing) {\r\n    return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n    const deferredPromise = new Deferred();\r\n    setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n    promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n    return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n    const params = [];\r\n    for (const [key, value] of Object.entries(querystringParams)) {\r\n        if (Array.isArray(value)) {\r\n            value.forEach(arrayVal => {\r\n                params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n            });\r\n        }\r\n        else {\r\n            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n        }\r\n    }\r\n    return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n    const obj = {};\r\n    const tokens = querystring.replace(/^\\?/, '').split('&');\r\n    tokens.forEach(token => {\r\n        if (token) {\r\n            const [key, value] = token.split('=');\r\n            obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n        }\r\n    });\r\n    return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n    const queryStart = url.indexOf('?');\r\n    if (!queryStart) {\r\n        return '';\r\n    }\r\n    const fragmentStart = url.indexOf('#', queryStart);\r\n    return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n *   var sha1 = new sha1();\r\n *   sha1.update(bytes);\r\n *   var hash = sha1.digest();\r\n *\r\n * Performance:\r\n *   Chrome 23:   ~400 Mbit/s\r\n *   Firefox 16:  ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n    constructor() {\r\n        /**\r\n         * Holds the previous values of accumulated variables a-e in the compress_\r\n         * function.\r\n         * @private\r\n         */\r\n        this.chain_ = [];\r\n        /**\r\n         * A buffer holding the partially computed hash result.\r\n         * @private\r\n         */\r\n        this.buf_ = [];\r\n        /**\r\n         * An array of 80 bytes, each a part of the message to be hashed.  Referred to\r\n         * as the message schedule in the docs.\r\n         * @private\r\n         */\r\n        this.W_ = [];\r\n        /**\r\n         * Contains data needed to pad messages less than 64 bytes.\r\n         * @private\r\n         */\r\n        this.pad_ = [];\r\n        /**\r\n         * @private {number}\r\n         */\r\n        this.inbuf_ = 0;\r\n        /**\r\n         * @private {number}\r\n         */\r\n        this.total_ = 0;\r\n        this.blockSize = 512 / 8;\r\n        this.pad_[0] = 128;\r\n        for (let i = 1; i < this.blockSize; ++i) {\r\n            this.pad_[i] = 0;\r\n        }\r\n        this.reset();\r\n    }\r\n    reset() {\r\n        this.chain_[0] = 0x67452301;\r\n        this.chain_[1] = 0xefcdab89;\r\n        this.chain_[2] = 0x98badcfe;\r\n        this.chain_[3] = 0x10325476;\r\n        this.chain_[4] = 0xc3d2e1f0;\r\n        this.inbuf_ = 0;\r\n        this.total_ = 0;\r\n    }\r\n    /**\r\n     * Internal compress helper function.\r\n     * @param buf Block to compress.\r\n     * @param offset Offset of the block in the buffer.\r\n     * @private\r\n     */\r\n    compress_(buf, offset) {\r\n        if (!offset) {\r\n            offset = 0;\r\n        }\r\n        const W = this.W_;\r\n        // get 16 big endian words\r\n        if (typeof buf === 'string') {\r\n            for (let i = 0; i < 16; i++) {\r\n                // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n                // have a bug that turns the post-increment ++ operator into pre-increment\r\n                // during JIT compilation.  We have code that depends heavily on SHA-1 for\r\n                // correctness and which is affected by this bug, so I've removed all uses\r\n                // of post-increment ++ in which the result value is used.  We can revert\r\n                // this change once the Safari bug\r\n                // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n                // most clients have been updated.\r\n                W[i] =\r\n                    (buf.charCodeAt(offset) << 24) |\r\n                        (buf.charCodeAt(offset + 1) << 16) |\r\n                        (buf.charCodeAt(offset + 2) << 8) |\r\n                        buf.charCodeAt(offset + 3);\r\n                offset += 4;\r\n            }\r\n        }\r\n        else {\r\n            for (let i = 0; i < 16; i++) {\r\n                W[i] =\r\n                    (buf[offset] << 24) |\r\n                        (buf[offset + 1] << 16) |\r\n                        (buf[offset + 2] << 8) |\r\n                        buf[offset + 3];\r\n                offset += 4;\r\n            }\r\n        }\r\n        // expand to 80 words\r\n        for (let i = 16; i < 80; i++) {\r\n            const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n            W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n        }\r\n        let a = this.chain_[0];\r\n        let b = this.chain_[1];\r\n        let c = this.chain_[2];\r\n        let d = this.chain_[3];\r\n        let e = this.chain_[4];\r\n        let f, k;\r\n        // TODO(user): Try to unroll this loop to speed up the computation.\r\n        for (let i = 0; i < 80; i++) {\r\n            if (i < 40) {\r\n                if (i < 20) {\r\n                    f = d ^ (b & (c ^ d));\r\n                    k = 0x5a827999;\r\n                }\r\n                else {\r\n                    f = b ^ c ^ d;\r\n                    k = 0x6ed9eba1;\r\n                }\r\n            }\r\n            else {\r\n                if (i < 60) {\r\n                    f = (b & c) | (d & (b | c));\r\n                    k = 0x8f1bbcdc;\r\n                }\r\n                else {\r\n                    f = b ^ c ^ d;\r\n                    k = 0xca62c1d6;\r\n                }\r\n            }\r\n            const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n            e = d;\r\n            d = c;\r\n            c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n            b = a;\r\n            a = t;\r\n        }\r\n        this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n        this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n        this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n        this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n        this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n    }\r\n    update(bytes, length) {\r\n        // TODO(johnlenz): tighten the function signature and remove this check\r\n        if (bytes == null) {\r\n            return;\r\n        }\r\n        if (length === undefined) {\r\n            length = bytes.length;\r\n        }\r\n        const lengthMinusBlock = length - this.blockSize;\r\n        let n = 0;\r\n        // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n        const buf = this.buf_;\r\n        let inbuf = this.inbuf_;\r\n        // The outer while loop should execute at most twice.\r\n        while (n < length) {\r\n            // When we have no data in the block to top up, we can directly process the\r\n            // input buffer (assuming it contains sufficient data). This gives ~25%\r\n            // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n            // the data is provided in large chunks (or in multiples of 64 bytes).\r\n            if (inbuf === 0) {\r\n                while (n <= lengthMinusBlock) {\r\n                    this.compress_(bytes, n);\r\n                    n += this.blockSize;\r\n                }\r\n            }\r\n            if (typeof bytes === 'string') {\r\n                while (n < length) {\r\n                    buf[inbuf] = bytes.charCodeAt(n);\r\n                    ++inbuf;\r\n                    ++n;\r\n                    if (inbuf === this.blockSize) {\r\n                        this.compress_(buf);\r\n                        inbuf = 0;\r\n                        // Jump to the outer loop so we use the full-block optimization.\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            else {\r\n                while (n < length) {\r\n                    buf[inbuf] = bytes[n];\r\n                    ++inbuf;\r\n                    ++n;\r\n                    if (inbuf === this.blockSize) {\r\n                        this.compress_(buf);\r\n                        inbuf = 0;\r\n                        // Jump to the outer loop so we use the full-block optimization.\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        this.inbuf_ = inbuf;\r\n        this.total_ += length;\r\n    }\r\n    /** @override */\r\n    digest() {\r\n        const digest = [];\r\n        let totalBits = this.total_ * 8;\r\n        // Add pad 0x80 0x00*.\r\n        if (this.inbuf_ < 56) {\r\n            this.update(this.pad_, 56 - this.inbuf_);\r\n        }\r\n        else {\r\n            this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n        }\r\n        // Add # bits.\r\n        for (let i = this.blockSize - 1; i >= 56; i--) {\r\n            this.buf_[i] = totalBits & 255;\r\n            totalBits /= 256; // Don't use bit-shifting here!\r\n        }\r\n        this.compress_(this.buf_);\r\n        let n = 0;\r\n        for (let i = 0; i < 5; i++) {\r\n            for (let j = 24; j >= 0; j -= 8) {\r\n                digest[n] = (this.chain_[i] >> j) & 255;\r\n                ++n;\r\n            }\r\n        }\r\n        return digest;\r\n    }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n *     as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n    const proxy = new ObserverProxy(executor, onNoObservers);\r\n    return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n    /**\r\n     * @param executor Function which can make calls to a single Observer\r\n     *     as a proxy.\r\n     * @param onNoObservers Callback when count of Observers goes to zero.\r\n     */\r\n    constructor(executor, onNoObservers) {\r\n        this.observers = [];\r\n        this.unsubscribes = [];\r\n        this.observerCount = 0;\r\n        // Micro-task scheduling by calling task.then().\r\n        this.task = Promise.resolve();\r\n        this.finalized = false;\r\n        this.onNoObservers = onNoObservers;\r\n        // Call the executor asynchronously so subscribers that are called\r\n        // synchronously after the creation of the subscribe function\r\n        // can still receive the very first value generated in the executor.\r\n        this.task\r\n            .then(() => {\r\n            executor(this);\r\n        })\r\n            .catch(e => {\r\n            this.error(e);\r\n        });\r\n    }\r\n    next(value) {\r\n        this.forEachObserver((observer) => {\r\n            observer.next(value);\r\n        });\r\n    }\r\n    error(error) {\r\n        this.forEachObserver((observer) => {\r\n            observer.error(error);\r\n        });\r\n        this.close(error);\r\n    }\r\n    complete() {\r\n        this.forEachObserver((observer) => {\r\n            observer.complete();\r\n        });\r\n        this.close();\r\n    }\r\n    /**\r\n     * Subscribe function that can be used to add an Observer to the fan-out list.\r\n     *\r\n     * - We require that no event is sent to a subscriber sychronously to their\r\n     *   call to subscribe().\r\n     */\r\n    subscribe(nextOrObserver, error, complete) {\r\n        let observer;\r\n        if (nextOrObserver === undefined &&\r\n            error === undefined &&\r\n            complete === undefined) {\r\n            throw new Error('Missing Observer.');\r\n        }\r\n        // Assemble an Observer object when passed as callback functions.\r\n        if (implementsAnyMethods(nextOrObserver, [\r\n            'next',\r\n            'error',\r\n            'complete'\r\n        ])) {\r\n            observer = nextOrObserver;\r\n        }\r\n        else {\r\n            observer = {\r\n                next: nextOrObserver,\r\n                error,\r\n                complete\r\n            };\r\n        }\r\n        if (observer.next === undefined) {\r\n            observer.next = noop;\r\n        }\r\n        if (observer.error === undefined) {\r\n            observer.error = noop;\r\n        }\r\n        if (observer.complete === undefined) {\r\n            observer.complete = noop;\r\n        }\r\n        const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n        // Attempt to subscribe to a terminated Observable - we\r\n        // just respond to the Observer with the final error or complete\r\n        // event.\r\n        if (this.finalized) {\r\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n            this.task.then(() => {\r\n                try {\r\n                    if (this.finalError) {\r\n                        observer.error(this.finalError);\r\n                    }\r\n                    else {\r\n                        observer.complete();\r\n                    }\r\n                }\r\n                catch (e) {\r\n                    // nothing\r\n                }\r\n                return;\r\n            });\r\n        }\r\n        this.observers.push(observer);\r\n        return unsub;\r\n    }\r\n    // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n    // any unsubscribed Observer.\r\n    unsubscribeOne(i) {\r\n        if (this.observers === undefined || this.observers[i] === undefined) {\r\n            return;\r\n        }\r\n        delete this.observers[i];\r\n        this.observerCount -= 1;\r\n        if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n            this.onNoObservers(this);\r\n        }\r\n    }\r\n    forEachObserver(fn) {\r\n        if (this.finalized) {\r\n            // Already closed by previous event....just eat the additional values.\r\n            return;\r\n        }\r\n        // Since sendOne calls asynchronously - there is no chance that\r\n        // this.observers will become undefined.\r\n        for (let i = 0; i < this.observers.length; i++) {\r\n            this.sendOne(i, fn);\r\n        }\r\n    }\r\n    // Call the Observer via one of it's callback function. We are careful to\r\n    // confirm that the observe has not been unsubscribed since this asynchronous\r\n    // function had been queued.\r\n    sendOne(i, fn) {\r\n        // Execute the callback asynchronously\r\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n        this.task.then(() => {\r\n            if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n                try {\r\n                    fn(this.observers[i]);\r\n                }\r\n                catch (e) {\r\n                    // Ignore exceptions raised in Observers or missing methods of an\r\n                    // Observer.\r\n                    // Log error to console. b/31404806\r\n                    if (typeof console !== 'undefined' && console.error) {\r\n                        console.error(e);\r\n                    }\r\n                }\r\n            }\r\n        });\r\n    }\r\n    close(err) {\r\n        if (this.finalized) {\r\n            return;\r\n        }\r\n        this.finalized = true;\r\n        if (err !== undefined) {\r\n            this.finalError = err;\r\n        }\r\n        // Proxy is no longer needed - garbage collect references\r\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n        this.task.then(() => {\r\n            this.observers = undefined;\r\n            this.onNoObservers = undefined;\r\n        });\r\n    }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n    return (...args) => {\r\n        Promise.resolve(true)\r\n            .then(() => {\r\n            fn(...args);\r\n        })\r\n            .catch((error) => {\r\n            if (onError) {\r\n                onError(error);\r\n            }\r\n        });\r\n    };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n    if (typeof obj !== 'object' || obj === null) {\r\n        return false;\r\n    }\r\n    for (const method of methods) {\r\n        if (method in obj && typeof obj[method] === 'function') {\r\n            return true;\r\n        }\r\n    }\r\n    return false;\r\n}\r\nfunction noop() {\r\n    // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n    let argError;\r\n    if (argCount < minCount) {\r\n        argError = 'at least ' + minCount;\r\n    }\r\n    else if (argCount > maxCount) {\r\n        argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n    }\r\n    if (argError) {\r\n        const error = fnName +\r\n            ' failed: Was called with ' +\r\n            argCount +\r\n            (argCount === 1 ? ' argument.' : ' arguments.') +\r\n            ' Expects ' +\r\n            argError +\r\n            '.';\r\n        throw new Error(error);\r\n    }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n    return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n    if (optional && !namespace) {\r\n        return;\r\n    }\r\n    if (typeof namespace !== 'string') {\r\n        //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n        throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n    }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n    if (optional && !callback) {\r\n        return;\r\n    }\r\n    if (typeof callback !== 'function') {\r\n        throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n    }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n    if (optional && !context) {\r\n        return;\r\n    }\r\n    if (typeof context !== 'object' || context === null) {\r\n        throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript.  All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n    const out = [];\r\n    let p = 0;\r\n    for (let i = 0; i < str.length; i++) {\r\n        let c = str.charCodeAt(i);\r\n        // Is this the lead surrogate in a surrogate pair?\r\n        if (c >= 0xd800 && c <= 0xdbff) {\r\n            const high = c - 0xd800; // the high 10 bits.\r\n            i++;\r\n            assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n            const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n            c = 0x10000 + (high << 10) + low;\r\n        }\r\n        if (c < 128) {\r\n            out[p++] = c;\r\n        }\r\n        else if (c < 2048) {\r\n            out[p++] = (c >> 6) | 192;\r\n            out[p++] = (c & 63) | 128;\r\n        }\r\n        else if (c < 65536) {\r\n            out[p++] = (c >> 12) | 224;\r\n            out[p++] = ((c >> 6) & 63) | 128;\r\n            out[p++] = (c & 63) | 128;\r\n        }\r\n        else {\r\n            out[p++] = (c >> 18) | 240;\r\n            out[p++] = ((c >> 12) & 63) | 128;\r\n            out[p++] = ((c >> 6) & 63) | 128;\r\n            out[p++] = (c & 63) | 128;\r\n        }\r\n    }\r\n    return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n    let p = 0;\r\n    for (let i = 0; i < str.length; i++) {\r\n        const c = str.charCodeAt(i);\r\n        if (c < 128) {\r\n            p++;\r\n        }\r\n        else if (c < 2048) {\r\n            p += 2;\r\n        }\r\n        else if (c >= 0xd800 && c <= 0xdbff) {\r\n            // Lead surrogate of a surrogate pair.  The pair together will take 4 bytes to represent.\r\n            p += 4;\r\n            i++; // skip trail surrogate.\r\n        }\r\n        else {\r\n            p += 3;\r\n        }\r\n    }\r\n    return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n        const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n        return v.toString(16);\r\n    });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n * <p>Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n * <p>Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n    // Calculates an exponentially increasing value.\r\n    // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n    // and count to restore state.\r\n    const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n    // A random \"fuzz\" to avoid waves of retries.\r\n    // Deviation: randomFactor is required.\r\n    const randomWait = Math.round(\r\n    // A fraction of the backoff value to add/subtract.\r\n    // Deviation: changes multiplication order to improve readability.\r\n    RANDOM_FACTOR *\r\n        currBaseValue *\r\n        // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n        // if we add or subtract.\r\n        (Math.random() - 0.5) *\r\n        2);\r\n    // Limits backoff to max to avoid effectively permanent backoff.\r\n    return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n    if (!Number.isFinite(i)) {\r\n        return `${i}`;\r\n    }\r\n    return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n    i = Math.abs(i);\r\n    const cent = i % 100;\r\n    if (cent >= 10 && cent <= 20) {\r\n        return 'th';\r\n    }\r\n    const dec = i % 10;\r\n    if (dec === 1) {\r\n        return 'st';\r\n    }\r\n    if (dec === 2) {\r\n        return 'nd';\r\n    }\r\n    if (dec === 3) {\r\n        return 'rd';\r\n    }\r\n    return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n    if (service && service._delegate) {\r\n        return service._delegate;\r\n    }\r\n    else {\r\n        return service;\r\n    }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import '@vaadin/vaadin-lumo-styles/color.js';\nimport '@vaadin/vaadin-lumo-styles/spacing.js';\nimport '@vaadin/vaadin-lumo-styles/style.js';\nimport '@vaadin/vaadin-lumo-styles/typography.js';\nimport { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\n\nregisterStyles(\n  'vaadin-notification-card',\n  css`\n    :host {\n      position: relative;\n      margin: var(--lumo-space-s);\n    }\n\n    [part='overlay'] {\n      background: var(--lumo-base-color) linear-gradient(var(--lumo-contrast-5pct), var(--lumo-contrast-5pct));\n      border-radius: var(--lumo-border-radius-l);\n      box-shadow: 0 0 0 1px var(--lumo-contrast-10pct), var(--lumo-box-shadow-l);\n      font-family: var(--lumo-font-family);\n      font-size: var(--lumo-font-size-m);\n      font-weight: 400;\n      line-height: var(--lumo-line-height-s);\n      letter-spacing: 0;\n      text-transform: none;\n      -webkit-text-size-adjust: 100%;\n      -webkit-font-smoothing: antialiased;\n      -moz-osx-font-smoothing: grayscale;\n    }\n\n    [part='content'] {\n      padding: var(--lumo-space-wide-l);\n      display: flex;\n      align-items: center;\n      justify-content: space-between;\n    }\n\n    [part='content'] ::slotted(vaadin-button) {\n      flex: none;\n      margin: 0 calc(var(--lumo-space-s) * -1) 0 var(--lumo-space-m);\n    }\n\n    :host([slot^='middle']) {\n      max-width: 80vw;\n      margin: var(--lumo-space-s) auto;\n    }\n\n    :host([slot\\$='stretch']) {\n      margin: 0;\n    }\n\n    :host([slot\\$='stretch']) [part='overlay'] {\n      border-radius: 0;\n    }\n\n    @media (min-width: 421px) {\n      :host(:not([slot\\$='stretch'])) {\n        display: flex;\n      }\n\n      :host([slot\\$='end']) {\n        justify-content: flex-end;\n      }\n\n      :host([slot^='middle']),\n      :host([slot\\$='center']) {\n        display: flex;\n        justify-content: center;\n      }\n    }\n\n    @keyframes lumo-notification-exit-fade-out {\n      100% {\n        opacity: 0;\n      }\n    }\n\n    @keyframes lumo-notification-enter-fade-in {\n      0% {\n        opacity: 0;\n      }\n    }\n\n    @keyframes lumo-notification-enter-slide-down {\n      0% {\n        transform: translateY(-200%);\n        opacity: 0;\n      }\n    }\n\n    @keyframes lumo-notification-exit-slide-up {\n      100% {\n        transform: translateY(-200%);\n        opacity: 0;\n      }\n    }\n\n    @keyframes lumo-notification-enter-slide-up {\n      0% {\n        transform: translateY(200%);\n        opacity: 0;\n      }\n    }\n\n    @keyframes lumo-notification-exit-slide-down {\n      100% {\n        transform: translateY(200%);\n        opacity: 0;\n      }\n    }\n\n    :host([slot='middle'][opening]) {\n      animation: lumo-notification-enter-fade-in 300ms;\n    }\n\n    :host([slot='middle'][closing]) {\n      animation: lumo-notification-exit-fade-out 300ms;\n    }\n\n    :host([slot^='top'][opening]) {\n      animation: lumo-notification-enter-slide-down 300ms;\n    }\n\n    :host([slot^='top'][closing]) {\n      animation: lumo-notification-exit-slide-up 300ms;\n    }\n\n    :host([slot^='bottom'][opening]) {\n      animation: lumo-notification-enter-slide-up 300ms;\n    }\n\n    :host([slot^='bottom'][closing]) {\n      animation: lumo-notification-exit-slide-down 300ms;\n    }\n\n    :host([theme~='primary']) [part='overlay'] {\n      background: var(--lumo-primary-color);\n      color: var(--lumo-primary-contrast-color);\n      box-shadow: var(--lumo-box-shadow-l);\n    }\n\n    :host([theme~='primary']) {\n      --_lumo-button-background-color: var(--lumo-shade-20pct);\n      --_lumo-button-color: var(--lumo-primary-contrast-color);\n      --_lumo-button-primary-background-color: var(--lumo-primary-contrast-color);\n      --_lumo-button-primary-color: var(--lumo-primary-text-color);\n    }\n\n    :host([theme~='contrast']) [part='overlay'] {\n      background: var(--lumo-contrast);\n      color: var(--lumo-base-color);\n      box-shadow: var(--lumo-box-shadow-l);\n    }\n\n    :host([theme~='contrast']) {\n      --_lumo-button-background-color: var(--lumo-contrast-20pct);\n      --_lumo-button-color: var(--lumo-base-color);\n      --_lumo-button-primary-background-color: var(--lumo-base-color);\n      --_lumo-button-primary-color: var(--lumo-contrast);\n    }\n\n    :host([theme~='success']) [part='overlay'] {\n      background: var(--lumo-success-color);\n      color: var(--lumo-success-contrast-color);\n      box-shadow: var(--lumo-box-shadow-l);\n    }\n\n    :host([theme~='success']) {\n      --_lumo-button-background-color: var(--lumo-shade-20pct);\n      --_lumo-button-color: var(--lumo-success-contrast-color);\n      --_lumo-button-primary-background-color: var(--lumo-success-contrast-color);\n      --_lumo-button-primary-color: var(--lumo-success-text-color);\n    }\n\n    :host([theme~='error']) [part='overlay'] {\n      background: var(--lumo-error-color);\n      color: var(--lumo-error-contrast-color);\n      box-shadow: var(--lumo-box-shadow-l);\n    }\n\n    :host([theme~='error']) {\n      --_lumo-button-background-color: var(--lumo-shade-20pct);\n      --_lumo-button-color: var(--lumo-error-contrast-color);\n      --_lumo-button-primary-background-color: var(--lumo-error-contrast-color);\n      --_lumo-button-primary-color: var(--lumo-error-text-color);\n    }\n\n    :host([theme~='warning']) [part='overlay'] {\n      background: var(--lumo-warning-color);\n      color: var(--lumo-warning-contrast-color);\n      box-shadow: inset 0 0 0 1px var(--lumo-contrast-20pct), var(--lumo-box-shadow-l);\n    }\n\n    :host([theme~='warning']) {\n      --_lumo-button-background-color: var(--lumo-shade-20pct);\n      --_lumo-button-color: var(--lumo-warning-contrast-color);\n      --_lumo-button-primary-background-color: var(--lumo-shade-50pct);\n      --_lumo-button-primary-color: var(--lumo-primary-contrast-color);\n    }\n  `,\n  { moduleId: 'lumo-notification-card' },\n);\n","/**\n * @license\n * Copyright (c) 2017 - 2023 Vaadin Ltd.\n * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/\n */\nimport { html, PolymerElement } from '@polymer/polymer/polymer-element.js';\nimport { render } from 'lit';\nimport { isTemplateResult } from 'lit/directive-helpers.js';\nimport { isIOS } from '@vaadin/component-base/src/browser-utils.js';\nimport { ElementMixin } from '@vaadin/component-base/src/element-mixin.js';\nimport { OverlayClassMixin } from '@vaadin/component-base/src/overlay-class-mixin.js';\nimport { processTemplates } from '@vaadin/component-base/src/templates.js';\nimport { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';\nimport { ThemePropertyMixin } from '@vaadin/vaadin-themable-mixin/vaadin-theme-property-mixin.js';\n\n/**\n * An element used internally by `<vaadin-notification>`. Not intended to be used separately.\n *\n * @extends HTMLElement\n * @mixes ElementMixin\n * @mixes ThemableMixin\n * @private\n */\nclass NotificationContainer extends ThemableMixin(ElementMixin(PolymerElement)) {\n  static get template() {\n    return html`\n      <style>\n        :host {\n          position: fixed;\n          z-index: 1000;\n          top: 0;\n          left: 0;\n          bottom: 0;\n          right: 0;\n          box-sizing: border-box;\n\n          display: flex;\n          flex-direction: column;\n          align-items: stretch;\n          pointer-events: none;\n        }\n\n        [region-group] {\n          flex: 1 1 0%;\n          display: flex;\n        }\n\n        [region-group='top'] {\n          align-items: flex-start;\n        }\n\n        [region-group='bottom'] {\n          align-items: flex-end;\n        }\n\n        [region-group] > [region] {\n          flex: 1 1 0%;\n        }\n\n        @media (max-width: 420px) {\n          [region-group] {\n            flex-direction: column;\n            align-items: stretch;\n          }\n\n          [region-group='top'] {\n            justify-content: flex-start;\n          }\n\n          [region-group='bottom'] {\n            justify-content: flex-end;\n          }\n\n          [region-group] > [region] {\n            flex: initial;\n          }\n        }\n      </style>\n\n      <div region=\"top-stretch\"><slot name=\"top-stretch\"></slot></div>\n      <div region-group=\"top\">\n        <div region=\"top-start\"><slot name=\"top-start\"></slot></div>\n        <div region=\"top-center\"><slot name=\"top-center\"></slot></div>\n        <div region=\"top-end\"><slot name=\"top-end\"></slot></div>\n      </div>\n      <div region=\"middle\"><slot name=\"middle\"></slot></div>\n      <div region-group=\"bottom\">\n        <div region=\"bottom-start\"><slot name=\"bottom-start\"></slot></div>\n        <div region=\"bottom-center\"><slot name=\"bottom-center\"></slot></div>\n        <div region=\"bottom-end\"><slot name=\"bottom-end\"></slot></div>\n      </div>\n      <div region=\"bottom-stretch\"><slot name=\"bottom-stretch\"></slot></div>\n    `;\n  }\n\n  static get is() {\n    return 'vaadin-notification-container';\n  }\n\n  static get properties() {\n    return {\n      /**\n       * True when the container is opened\n       * @type {boolean}\n       */\n      opened: {\n        type: Boolean,\n        value: false,\n        observer: '_openedChanged',\n      },\n    };\n  }\n\n  constructor() {\n    super();\n\n    this._boundVaadinOverlayClose = this._onVaadinOverlayClose.bind(this);\n    if (isIOS) {\n      this._boundIosResizeListener = () => this._detectIosNavbar();\n    }\n  }\n\n  /** @private */\n  _openedChanged(opened) {\n    if (opened) {\n      document.body.appendChild(this);\n      document.addEventListener('vaadin-overlay-close', this._boundVaadinOverlayClose);\n      if (this._boundIosResizeListener) {\n        this._detectIosNavbar();\n        window.addEventListener('resize', this._boundIosResizeListener);\n      }\n    } else {\n      document.body.removeChild(this);\n      document.removeEventListener('vaadin-overlay-close', this._boundVaadinOverlayClose);\n      if (this._boundIosResizeListener) {\n        window.removeEventListener('resize', this._boundIosResizeListener);\n      }\n    }\n  }\n\n  /** @private */\n  _detectIosNavbar() {\n    const innerHeight = window.innerHeight;\n    const innerWidth = window.innerWidth;\n    const landscape = innerWidth > innerHeight;\n    const clientHeight = document.documentElement.clientHeight;\n    if (landscape && clientHeight > innerHeight) {\n      this.style.bottom = `${clientHeight - innerHeight}px`;\n    } else {\n      this.style.bottom = '0';\n    }\n  }\n\n  /** @private */\n  _onVaadinOverlayClose(event) {\n    // Notifications are a separate overlay mechanism from vaadin-overlay, and\n    // interacting with them should not close modal overlays\n    const sourceEvent = event.detail.sourceEvent;\n    const isFromNotification = sourceEvent && sourceEvent.composedPath().indexOf(this) >= 0;\n    if (isFromNotification) {\n      event.preventDefault();\n    }\n  }\n}\n\n/**\n * An element used internally by `<vaadin-notification>`. Not intended to be used separately.\n *\n * @extends HTMLElement\n * @mixes ThemableMixin\n * @private\n */\nclass NotificationCard extends ThemableMixin(PolymerElement) {\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: block;\n        }\n\n        [part='overlay'] {\n          pointer-events: auto;\n        }\n\n        @media (forced-colors: active) {\n          [part='overlay'] {\n            outline: 3px solid;\n          }\n        }\n      </style>\n\n      <div part=\"overlay\">\n        <div part=\"content\">\n          <slot></slot>\n        </div>\n      </div>\n    `;\n  }\n\n  static get is() {\n    return 'vaadin-notification-card';\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n    this.setAttribute('role', 'alert');\n    this.setAttribute('aria-live', 'polite');\n  }\n}\n\n/**\n * `<vaadin-notification>` is a Web Component providing accessible and customizable notifications (toasts).\n *\n * ### Rendering\n *\n * The content of the notification can be populated by using the renderer callback function.\n *\n * The renderer function provides `root`, `notification` arguments.\n * Generate DOM content, append it to the `root` element and control the state\n * of the host element by accessing `notification`. Before generating new content,\n * users are able to check if there is already content in `root` for reusing it.\n *\n * ```html\n * <vaadin-notification id=\"notification\"></vaadin-notification>\n * ```\n * ```js\n * const notification = document.querySelector('#notification');\n * notification.renderer = function(root, notification) {\n *   root.textContent = \"Your work has been saved\";\n * };\n * ```\n *\n * Renderer is called on the opening of the notification.\n * DOM generated during the renderer call can be reused\n * in the next renderer call and will be provided with the `root` argument.\n * On first call it will be empty.\n *\n * ### Styling\n *\n * `<vaadin-notification>` uses `<vaadin-notification-card>` internal\n * themable component as the actual visible notification cards.\n *\n * The following shadow DOM parts of the `<vaadin-notification-card>` are available for styling:\n *\n * Part name | Description\n * ----------------|----------------\n * `overlay` | The notification container\n * `content` | The content of the notification\n *\n * See [Styling Components](https://vaadin.com/docs/latest/styling/styling-components) documentation.\n *\n * Note: the `theme` attribute value set on `<vaadin-notification>` is\n * propagated to the internal `<vaadin-notification-card>`.\n *\n * @fires {CustomEvent} opened-changed - Fired when the `opened` property changes.\n *\n * @extends HTMLElement\n * @mixes ThemePropertyMixin\n * @mixes ElementMixin\n * @mixes OverlayClassMixin\n */\nclass Notification extends OverlayClassMixin(ThemePropertyMixin(ElementMixin(PolymerElement))) {\n  static get template() {\n    return html`\n      <style>\n        :host {\n          display: none !important;\n        }\n      </style>\n      <vaadin-notification-card theme$=\"[[_theme]]\"> </vaadin-notification-card>\n    `;\n  }\n\n  static get is() {\n    return 'vaadin-notification';\n  }\n\n  static get properties() {\n    return {\n      /**\n       * The duration in milliseconds to show the notification.\n       * Set to `0` or a negative number to disable the notification auto-closing.\n       * @type {number}\n       */\n      duration: {\n        type: Number,\n        value: 5000,\n      },\n\n      /**\n       * True if the notification is currently displayed.\n       * @type {boolean}\n       */\n      opened: {\n        type: Boolean,\n        value: false,\n        notify: true,\n        observer: '_openedChanged',\n      },\n\n      /**\n       * Alignment of the notification in the viewport\n       * Valid values are `top-stretch|top-start|top-center|top-end|middle|bottom-start|bottom-center|bottom-end|bottom-stretch`\n       * @type {!NotificationPosition}\n       */\n      position: {\n        type: String,\n        value: 'bottom-start',\n        observer: '_positionChanged',\n      },\n\n      /**\n       * Custom function for rendering the content of the notification.\n       * Receives two arguments:\n       *\n       * - `root` The `<vaadin-notification-card>` DOM element. Append\n       *   your content to it.\n       * - `notification` The reference to the `<vaadin-notification>` element.\n       * @type {!NotificationRenderer | undefined}\n       */\n      renderer: Function,\n    };\n  }\n\n  static get observers() {\n    return ['_durationChanged(duration, opened)', '_rendererChanged(renderer, opened, _overlayElement)'];\n  }\n\n  /**\n   * Shows a notification with the given content.\n   * By default, positions the notification at `bottom-start` and uses a 5 second duration.\n   * An options object can be passed to configure the notification.\n   * The options object has the following structure:\n   *\n   * ```\n   * {\n   *   position?: string\n   *   duration?: number\n   *   theme?: string\n   * }\n   * ```\n   *\n   * See the individual documentation for:\n   * - [`position`](#/elements/vaadin-notification#property-position)\n   * - [`duration`](#/elements/vaadin-notification#property-duration)\n   *\n   * @param contents the contents to show, either as a string or a Lit template.\n   * @param options optional options for customizing the notification.\n   */\n  static show(contents, options) {\n    if (isTemplateResult(contents)) {\n      return Notification._createAndShowNotification((root) => {\n        render(contents, root);\n      }, options);\n    }\n    return Notification._createAndShowNotification((root) => {\n      root.innerText = contents;\n    }, options);\n  }\n\n  /** @private */\n  static _createAndShowNotification(renderer, options) {\n    const notification = document.createElement(Notification.is);\n    if (options && Number.isFinite(options.duration)) {\n      notification.duration = options.duration;\n    }\n    if (options && options.position) {\n      notification.position = options.position;\n    }\n    if (options && options.theme) {\n      notification.setAttribute('theme', options.theme);\n    }\n    notification.renderer = renderer;\n    document.body.appendChild(notification);\n    notification.opened = true;\n\n    notification.addEventListener('opened-changed', (e) => {\n      if (!e.detail.value) {\n        notification.remove();\n      }\n    });\n\n    return notification;\n  }\n\n  /** @private */\n  get _container() {\n    if (!Notification._container) {\n      Notification._container = document.createElement('vaadin-notification-container');\n      document.body.appendChild(Notification._container);\n    }\n    return Notification._container;\n  }\n\n  /** @protected */\n  get _card() {\n    return this._overlayElement;\n  }\n\n  /** @protected */\n  ready() {\n    super.ready();\n\n    this._overlayElement = this.shadowRoot.querySelector('vaadin-notification-card');\n\n    processTemplates(this);\n  }\n\n  /** @protected */\n  disconnectedCallback() {\n    super.disconnectedCallback();\n    queueMicrotask(() => {\n      if (!this.isConnected) {\n        this.opened = false;\n      }\n    });\n  }\n\n  /**\n   * Requests an update for the content of the notification.\n   * While performing the update, it invokes the renderer passed in the `renderer` property.\n   *\n   * It is not guaranteed that the update happens immediately (synchronously) after it is requested.\n   */\n  requestContentUpdate() {\n    if (!this.renderer) {\n      return;\n    }\n\n    this.renderer(this._card, this);\n  }\n\n  /** @private */\n  _rendererChanged(renderer, opened, card) {\n    if (!card) {\n      return;\n    }\n\n    const rendererChanged = this._oldRenderer !== renderer;\n    this._oldRenderer = renderer;\n\n    if (rendererChanged) {\n      card.innerHTML = '';\n      // Whenever a Lit-based renderer is used, it assigns a Lit part to the node it was rendered into.\n      // When clearing the rendered content, this part needs to be manually disposed of.\n      // Otherwise, using a Lit-based renderer on the same node will throw an exception or render nothing afterward.\n      delete card._$litPart$;\n    }\n\n    if (opened) {\n      if (!this._didAnimateNotificationAppend) {\n        this._animatedAppendNotificationCard();\n      }\n      this.requestContentUpdate();\n    }\n  }\n\n  /**\n   * Opens the notification.\n   */\n  open() {\n    this.opened = true;\n  }\n\n  /**\n   * Closes the notification.\n   */\n  close() {\n    this.opened = false;\n  }\n\n  /** @private */\n  _openedChanged(opened) {\n    if (opened) {\n      this._container.opened = true;\n      this._animatedAppendNotificationCard();\n    } else if (this._card) {\n      this._closeNotificationCard();\n    }\n  }\n\n  /** @private */\n  _animatedAppendNotificationCard() {\n    if (this._card) {\n      this._card.setAttribute('opening', '');\n      this._appendNotificationCard();\n      const listener = () => {\n        this._card.removeEventListener('animationend', listener);\n        this._card.removeAttribute('opening');\n      };\n      this._card.addEventListener('animationend', listener);\n      this._didAnimateNotificationAppend = true;\n    } else {\n      this._didAnimateNotificationAppend = false;\n    }\n  }\n\n  /** @private */\n  _appendNotificationCard() {\n    if (!this._card) {\n      return;\n    }\n\n    if (!this._container.shadowRoot.querySelector(`slot[name=\"${this.position}\"]`)) {\n      console.warn(`Invalid alignment parameter provided: position=${this.position}`);\n      return;\n    }\n\n    this._card.slot = this.position;\n    if (this._container.firstElementChild && /top/u.test(this.position)) {\n      this._container.insertBefore(this._card, this._container.firstElementChild);\n    } else {\n      this._container.appendChild(this._card);\n    }\n  }\n\n  /** @private */\n  _removeNotificationCard() {\n    if (this._card.parentNode) {\n      this._card.parentNode.removeChild(this._card);\n    }\n    this._card.removeAttribute('closing');\n    this._container.opened = Boolean(this._container.firstElementChild);\n  }\n\n  /** @private */\n  _closeNotificationCard() {\n    if (this._durationTimeoutId) {\n      clearTimeout(this._durationTimeoutId);\n    }\n    this._animatedRemoveNotificationCard();\n  }\n\n  /** @private */\n  _animatedRemoveNotificationCard() {\n    this._card.setAttribute('closing', '');\n    const name = getComputedStyle(this._card).getPropertyValue('animation-name');\n    if (name && name !== 'none') {\n      const listener = () => {\n        this._removeNotificationCard();\n        this._card.removeEventListener('animationend', listener);\n      };\n      this._card.addEventListener('animationend', listener);\n    } else {\n      this._removeNotificationCard();\n    }\n  }\n\n  /** @private */\n  _positionChanged() {\n    if (this.opened) {\n      this._animatedAppendNotificationCard();\n    }\n  }\n\n  /** @private */\n  _durationChanged(duration, opened) {\n    if (opened) {\n      clearTimeout(this._durationTimeoutId);\n      if (duration > 0) {\n        this._durationTimeoutId = setTimeout(() => this.close(), duration);\n      }\n    }\n  }\n}\n\ncustomElements.define(NotificationContainer.is, NotificationContainer);\ncustomElements.define(NotificationCard.is, NotificationCard);\ncustomElements.define(Notification.is, Notification);\n\nexport { Notification };\n","function toArray(objectOrArray) {\n  objectOrArray = objectOrArray || [];\n  return Array.isArray(objectOrArray) ? objectOrArray : [objectOrArray];\n}\n\nfunction log(msg) {\n  return `[Vaadin.Router] ${msg}`;\n}\n\nfunction logValue(value) {\n  if (typeof value !== 'object') {\n    return String(value);\n  }\n\n  const stringType = Object.prototype.toString.call(value).match(/ (.*)\\]$/)[1];\n  if (stringType === 'Object' || stringType === 'Array') {\n    return `${stringType} ${JSON.stringify(value)}`;\n  } else {\n    return stringType;\n  }\n}\n\nconst MODULE = 'module';\nconst NOMODULE = 'nomodule';\nconst bundleKeys = [MODULE, NOMODULE];\n\nfunction ensureBundle(src) {\n  if (!src.match(/.+\\.[m]?js$/)) {\n    throw new Error(\n      log(`Unsupported type for bundle \"${src}\": .js or .mjs expected.`)\n    );\n  }\n}\n\nfunction ensureRoute(route) {\n  if (!route || !isString(route.path)) {\n    throw new Error(\n      log(`Expected route config to be an object with a \"path\" string property, or an array of such objects`)\n    );\n  }\n\n  const bundle = route.bundle;\n\n  const stringKeys = ['component', 'redirect', 'bundle'];\n  if (\n    !isFunction(route.action) &&\n    !Array.isArray(route.children) &&\n    !isFunction(route.children) &&\n    !isObject(bundle) &&\n    !stringKeys.some(key => isString(route[key]))\n  ) {\n    throw new Error(\n      log(\n        `Expected route config \"${route.path}\" to include either \"${stringKeys.join('\", \"')}\" ` +\n        `or \"action\" function but none found.`\n      )\n    );\n  }\n\n  if (bundle) {\n    if (isString(bundle)) {\n      ensureBundle(bundle);\n    } else if (!bundleKeys.some(key => key in bundle)) {\n      throw new Error(\n        log('Expected route bundle to include either \"' + NOMODULE + '\" or \"' + MODULE + '\" keys, or both')\n      );\n    } else {\n      bundleKeys.forEach(key => key in bundle && ensureBundle(bundle[key]));\n    }\n  }\n\n  if (route.redirect) {\n    ['bundle', 'component'].forEach(overriddenProp => {\n      if (overriddenProp in route) {\n        console.warn(\n          log(\n            `Route config \"${route.path}\" has both \"redirect\" and \"${overriddenProp}\" properties, ` +\n            `and \"redirect\" will always override the latter. Did you mean to only use \"${overriddenProp}\"?`\n          )\n        );\n      }\n    });\n  }\n}\n\nfunction ensureRoutes(routes) {\n  toArray(routes).forEach(route => ensureRoute(route));\n}\n\nfunction loadScript(src, key) {\n  let script = document.head.querySelector('script[src=\"' + src + '\"][async]');\n  if (!script) {\n    script = document.createElement('script');\n    script.setAttribute('src', src);\n    if (key === MODULE) {\n      script.setAttribute('type', MODULE);\n    } else if (key === NOMODULE) {\n      script.setAttribute(NOMODULE, '');\n    }\n    script.async = true;\n  }\n  return new Promise((resolve, reject) => {\n    script.onreadystatechange = script.onload = e => {\n      script.__dynamicImportLoaded = true;\n      resolve(e);\n    };\n    script.onerror = e => {\n      if (script.parentNode) {\n        script.parentNode.removeChild(script);\n      }\n      reject(e);\n    };\n    if (script.parentNode === null) {\n      document.head.appendChild(script);\n    } else if (script.__dynamicImportLoaded) {\n      resolve();\n    }\n  });\n}\n\nfunction loadBundle(bundle) {\n  if (isString(bundle)) {\n    return loadScript(bundle);\n  } else {\n    return Promise.race(\n      bundleKeys\n        .filter(key => key in bundle)\n        .map(key => loadScript(bundle[key], key))\n    );\n  }\n}\n\nfunction fireRouterEvent(type, detail) {\n  return !window.dispatchEvent(new CustomEvent(\n    `vaadin-router-${type}`,\n    {cancelable: type === 'go', detail}\n  ));\n}\n\nfunction isObject(o) {\n  // guard against null passing the typeof check\n  return typeof o === 'object' && !!o;\n}\n\nfunction isFunction(f) {\n  return typeof f === 'function';\n}\n\nfunction isString(s) {\n  return typeof s === 'string';\n}\n\nfunction getNotFoundError(context) {\n  const error = new Error(log(`Page not found (${context.pathname})`));\n  error.context = context;\n  error.code = 404;\n  return error;\n}\n\nconst notFoundResult = new (class NotFoundResult {})();\n\n/* istanbul ignore next: coverage is calculated in Chrome, this code is for IE */\nfunction getAnchorOrigin(anchor) {\n  // IE11: on HTTP and HTTPS the default port is not included into\n  // window.location.origin, so won't include it here either.\n  const port = anchor.port;\n  const protocol = anchor.protocol;\n  const defaultHttp = protocol === 'http:' && port === '80';\n  const defaultHttps = protocol === 'https:' && port === '443';\n  const host = (defaultHttp || defaultHttps)\n    ? anchor.hostname // does not include the port number (e.g. www.example.org)\n    : anchor.host; // does include the port number (e.g. www.example.org:80)\n  return `${protocol}//${host}`;\n}\n\n// The list of checks is not complete:\n//  - SVG support is missing\n//  - the 'rel' attribute is not considered\nfunction vaadinRouterGlobalClickHandler(event) {\n  // ignore the click if the default action is prevented\n  if (event.defaultPrevented) {\n    return;\n  }\n\n  // ignore the click if not with the primary mouse button\n  if (event.button !== 0) {\n    return;\n  }\n\n  // ignore the click if a modifier key is pressed\n  if (event.shiftKey || event.ctrlKey || event.altKey || event.metaKey) {\n    return;\n  }\n\n  // find the <a> element that the click is at (or within)\n  let anchor = event.target;\n  const path = event.composedPath\n    ? event.composedPath()\n    : (event.path || []);\n\n  // FIXME(web-padawan): `Symbol.iterator` used by webcomponentsjs is broken for arrays\n  // example to check: `for...of` loop here throws the \"Not yet implemented\" error\n  for (let i = 0; i < path.length; i++) {\n    const target = path[i];\n    if (target.nodeName && target.nodeName.toLowerCase() === 'a') {\n      anchor = target;\n      break;\n    }\n  }\n\n  while (anchor && anchor.nodeName.toLowerCase() !== 'a') {\n    anchor = anchor.parentNode;\n  }\n\n  // ignore the click if not at an <a> element\n  if (!anchor || anchor.nodeName.toLowerCase() !== 'a') {\n    return;\n  }\n\n  // ignore the click if the <a> element has a non-default target\n  if (anchor.target && anchor.target.toLowerCase() !== '_self') {\n    return;\n  }\n\n  // ignore the click if the <a> element has the 'download' attribute\n  if (anchor.hasAttribute('download')) {\n    return;\n  }\n\n  // ignore the click if the <a> element has the 'router-ignore' attribute\n  if (anchor.hasAttribute('router-ignore')) {\n    return;\n  }\n\n  // ignore the click if the target URL is a fragment on the current page\n  if (anchor.pathname === window.location.pathname && anchor.hash !== '') {\n    return;\n  }\n\n  // ignore the click if the target is external to the app\n  // In IE11 HTMLAnchorElement does not have the `origin` property\n  const origin = anchor.origin || getAnchorOrigin(anchor);\n  if (origin !== window.location.origin) {\n    return;\n  }\n\n  // if none of the above, convert the click into a navigation event\n  const {pathname, search, hash} = anchor;\n  if (fireRouterEvent('go', {pathname, search, hash})) {\n    event.preventDefault();\n    // for a click event, the scroll is reset to the top position.\n    if (event && event.type === 'click') {\n      window.scrollTo(0, 0);\n    }\n  }\n}\n\n/**\n * A navigation trigger for Vaadin Router that translated clicks on `<a>` links\n * into Vaadin Router navigation events.\n *\n * Only regular clicks on in-app links are translated (primary mouse button, no\n * modifier keys, the target href is within the app's URL space).\n *\n * @memberOf Router.NavigationTrigger\n * @type {NavigationTrigger}\n */\nconst CLICK = {\n  activate() {\n    window.document.addEventListener('click', vaadinRouterGlobalClickHandler);\n  },\n\n  inactivate() {\n    window.document.removeEventListener('click', vaadinRouterGlobalClickHandler);\n  }\n};\n\n// PopStateEvent constructor shim\nconst isIE = /Trident/.test(navigator.userAgent);\n\n/* istanbul ignore next: coverage is calculated in Chrome, this code is for IE */\nif (isIE && !isFunction(window.PopStateEvent)) {\n  window.PopStateEvent = function(inType, params) {\n    params = params || {};\n    var e = document.createEvent('Event');\n    e.initEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable));\n    e.state = params.state || null;\n    return e;\n  };\n  window.PopStateEvent.prototype = window.Event.prototype;\n}\n\nfunction vaadinRouterGlobalPopstateHandler(event) {\n  if (event.state === 'vaadin-router-ignore') {\n    return;\n  }\n  const {pathname, search, hash} = window.location;\n  fireRouterEvent('go', {pathname, search, hash});\n}\n\n/**\n * A navigation trigger for Vaadin Router that translates popstate events into\n * Vaadin Router navigation events.\n *\n * @memberOf Router.NavigationTrigger\n * @type {NavigationTrigger}\n */\nconst POPSTATE = {\n  activate() {\n    window.addEventListener('popstate', vaadinRouterGlobalPopstateHandler);\n  },\n\n  inactivate() {\n    window.removeEventListener('popstate', vaadinRouterGlobalPopstateHandler);\n  }\n};\n\n/**\n * Expose `pathToRegexp`.\n */\nvar pathToRegexp_1 = pathToRegexp$1;\nvar parse_1 = parse;\nvar compile_1 = compile;\nvar tokensToFunction_1 = tokensToFunction;\nvar tokensToRegExp_1 = tokensToRegExp;\n\n/**\n * Default configs.\n */\nvar DEFAULT_DELIMITER = '/';\nvar DEFAULT_DELIMITERS = './';\n\n/**\n * The main path matching regexp utility.\n *\n * @type {RegExp}\n */\nvar PATH_REGEXP = new RegExp([\n  // Match escaped characters that would otherwise appear in future matches.\n  // This allows the user to escape special characters that won't transform.\n  '(\\\\\\\\.)',\n  // Match Express-style parameters and un-named parameters with a prefix\n  // and optional suffixes. Matches appear as:\n  //\n  // \":test(\\\\d+)?\" => [\"test\", \"\\d+\", undefined, \"?\"]\n  // \"(\\\\d+)\"  => [undefined, undefined, \"\\d+\", undefined]\n  '(?:\\\\:(\\\\w+)(?:\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))?|\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))([+*?])?'\n].join('|'), 'g');\n\n/**\n * Parse a string for the raw tokens.\n *\n * @param  {string}  str\n * @param  {Object=} options\n * @return {!Array}\n */\nfunction parse (str, options) {\n  var tokens = [];\n  var key = 0;\n  var index = 0;\n  var path = '';\n  var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER;\n  var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS;\n  var pathEscaped = false;\n  var res;\n\n  while ((res = PATH_REGEXP.exec(str)) !== null) {\n    var m = res[0];\n    var escaped = res[1];\n    var offset = res.index;\n    path += str.slice(index, offset);\n    index = offset + m.length;\n\n    // Ignore already escaped sequences.\n    if (escaped) {\n      path += escaped[1];\n      pathEscaped = true;\n      continue\n    }\n\n    var prev = '';\n    var next = str[index];\n    var name = res[2];\n    var capture = res[3];\n    var group = res[4];\n    var modifier = res[5];\n\n    if (!pathEscaped && path.length) {\n      var k = path.length - 1;\n\n      if (delimiters.indexOf(path[k]) > -1) {\n        prev = path[k];\n        path = path.slice(0, k);\n      }\n    }\n\n    // Push the current path onto the tokens.\n    if (path) {\n      tokens.push(path);\n      path = '';\n      pathEscaped = false;\n    }\n\n    var partial = prev !== '' && next !== undefined && next !== prev;\n    var repeat = modifier === '+' || modifier === '*';\n    var optional = modifier === '?' || modifier === '*';\n    var delimiter = prev || defaultDelimiter;\n    var pattern = capture || group;\n\n    tokens.push({\n      name: name || key++,\n      prefix: prev,\n      delimiter: delimiter,\n      optional: optional,\n      repeat: repeat,\n      partial: partial,\n      pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?'\n    });\n  }\n\n  // Push any remaining characters.\n  if (path || index < str.length) {\n    tokens.push(path + str.substr(index));\n  }\n\n  return tokens\n}\n\n/**\n * Compile a string to a template function for the path.\n *\n * @param  {string}             str\n * @param  {Object=}            options\n * @return {!function(Object=, Object=)}\n */\nfunction compile (str, options) {\n  return tokensToFunction(parse(str, options))\n}\n\n/**\n * Expose a method for transforming tokens into the path function.\n */\nfunction tokensToFunction (tokens) {\n  // Compile all the tokens into regexps.\n  var matches = new Array(tokens.length);\n\n  // Compile all the patterns before compilation.\n  for (var i = 0; i < tokens.length; i++) {\n    if (typeof tokens[i] === 'object') {\n      matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');\n    }\n  }\n\n  return function (data, options) {\n    var path = '';\n    var encode = (options && options.encode) || encodeURIComponent;\n\n    for (var i = 0; i < tokens.length; i++) {\n      var token = tokens[i];\n\n      if (typeof token === 'string') {\n        path += token;\n        continue\n      }\n\n      var value = data ? data[token.name] : undefined;\n      var segment;\n\n      if (Array.isArray(value)) {\n        if (!token.repeat) {\n          throw new TypeError('Expected \"' + token.name + '\" to not repeat, but got array')\n        }\n\n        if (value.length === 0) {\n          if (token.optional) continue\n\n          throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n        }\n\n        for (var j = 0; j < value.length; j++) {\n          segment = encode(value[j], token);\n\n          if (!matches[i].test(segment)) {\n            throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\"')\n          }\n\n          path += (j === 0 ? token.prefix : token.delimiter) + segment;\n        }\n\n        continue\n      }\n\n      if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n        segment = encode(String(value), token);\n\n        if (!matches[i].test(segment)) {\n          throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but got \"' + segment + '\"')\n        }\n\n        path += token.prefix + segment;\n        continue\n      }\n\n      if (token.optional) {\n        // Prepend partial segment prefixes.\n        if (token.partial) path += token.prefix;\n\n        continue\n      }\n\n      throw new TypeError('Expected \"' + token.name + '\" to be ' + (token.repeat ? 'an array' : 'a string'))\n    }\n\n    return path\n  }\n}\n\n/**\n * Escape a regular expression string.\n *\n * @param  {string} str\n * @return {string}\n */\nfunction escapeString (str) {\n  return str.replace(/([.+*?=^!:${}()[\\]|/\\\\])/g, '\\\\$1')\n}\n\n/**\n * Escape the capturing group by escaping special characters and meaning.\n *\n * @param  {string} group\n * @return {string}\n */\nfunction escapeGroup (group) {\n  return group.replace(/([=!:$/()])/g, '\\\\$1')\n}\n\n/**\n * Get the flags for a regexp from the options.\n *\n * @param  {Object} options\n * @return {string}\n */\nfunction flags (options) {\n  return options && options.sensitive ? '' : 'i'\n}\n\n/**\n * Pull out keys from a regexp.\n *\n * @param  {!RegExp} path\n * @param  {Array=}  keys\n * @return {!RegExp}\n */\nfunction regexpToRegexp (path, keys) {\n  if (!keys) return path\n\n  // Use a negative lookahead to match only capturing groups.\n  var groups = path.source.match(/\\((?!\\?)/g);\n\n  if (groups) {\n    for (var i = 0; i < groups.length; i++) {\n      keys.push({\n        name: i,\n        prefix: null,\n        delimiter: null,\n        optional: false,\n        repeat: false,\n        partial: false,\n        pattern: null\n      });\n    }\n  }\n\n  return path\n}\n\n/**\n * Transform an array into a regexp.\n *\n * @param  {!Array}  path\n * @param  {Array=}  keys\n * @param  {Object=} options\n * @return {!RegExp}\n */\nfunction arrayToRegexp (path, keys, options) {\n  var parts = [];\n\n  for (var i = 0; i < path.length; i++) {\n    parts.push(pathToRegexp$1(path[i], keys, options).source);\n  }\n\n  return new RegExp('(?:' + parts.join('|') + ')', flags(options))\n}\n\n/**\n * Create a path regexp from string input.\n *\n * @param  {string}  path\n * @param  {Array=}  keys\n * @param  {Object=} options\n * @return {!RegExp}\n */\nfunction stringToRegexp (path, keys, options) {\n  return tokensToRegExp(parse(path, options), keys, options)\n}\n\n/**\n * Expose a function for taking tokens and returning a RegExp.\n *\n * @param  {!Array}  tokens\n * @param  {Array=}  keys\n * @param  {Object=} options\n * @return {!RegExp}\n */\nfunction tokensToRegExp (tokens, keys, options) {\n  options = options || {};\n\n  var strict = options.strict;\n  var start = options.start !== false;\n  var end = options.end !== false;\n  var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER);\n  var delimiters = options.delimiters || DEFAULT_DELIMITERS;\n  var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|');\n  var route = start ? '^' : '';\n  var isEndDelimited = tokens.length === 0;\n\n  // Iterate over the tokens and create our regexp string.\n  for (var i = 0; i < tokens.length; i++) {\n    var token = tokens[i];\n\n    if (typeof token === 'string') {\n      route += escapeString(token);\n      isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1;\n    } else {\n      var capture = token.repeat\n        ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*'\n        : token.pattern;\n\n      if (keys) keys.push(token);\n\n      if (token.optional) {\n        if (token.partial) {\n          route += escapeString(token.prefix) + '(' + capture + ')?';\n        } else {\n          route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?';\n        }\n      } else {\n        route += escapeString(token.prefix) + '(' + capture + ')';\n      }\n    }\n  }\n\n  if (end) {\n    if (!strict) route += '(?:' + delimiter + ')?';\n\n    route += endsWith === '$' ? '$' : '(?=' + endsWith + ')';\n  } else {\n    if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?';\n    if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')';\n  }\n\n  return new RegExp(route, flags(options))\n}\n\n/**\n * Normalize the given path string, returning a regular expression.\n *\n * An empty array can be passed in for the keys, which will hold the\n * placeholder key descriptions. For example, using `/user/:id`, `keys` will\n * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.\n *\n * @param  {(string|RegExp|Array)} path\n * @param  {Array=}                keys\n * @param  {Object=}               options\n * @return {!RegExp}\n */\nfunction pathToRegexp$1 (path, keys, options) {\n  if (path instanceof RegExp) {\n    return regexpToRegexp(path, keys)\n  }\n\n  if (Array.isArray(path)) {\n    return arrayToRegexp(/** @type {!Array} */ (path), keys, options)\n  }\n\n  return stringToRegexp(/** @type {string} */ (path), keys, options)\n}\npathToRegexp_1.parse = parse_1;\npathToRegexp_1.compile = compile_1;\npathToRegexp_1.tokensToFunction = tokensToFunction_1;\npathToRegexp_1.tokensToRegExp = tokensToRegExp_1;\n\n/**\n * Universal Router (https://www.kriasoft.com/universal-router/)\n *\n * Copyright (c) 2015-present Kriasoft.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.txt file in the root directory of this source tree.\n */\n\nconst {hasOwnProperty} = Object.prototype;\nconst cache$1 = new Map();\n// see https://github.com/pillarjs/path-to-regexp/issues/148\ncache$1.set('|false', {\n  keys: [],\n  pattern: /(?:)/\n});\n\nfunction decodeParam(val) {\n  try {\n    return decodeURIComponent(val);\n  } catch (err) {\n    return val;\n  }\n}\n\nfunction matchPath(routepath, path, exact, parentKeys, parentParams) {\n  exact = !!exact;\n  const cacheKey = `${routepath}|${exact}`;\n  let regexp = cache$1.get(cacheKey);\n\n  if (!regexp) {\n    const keys = [];\n    regexp = {\n      keys,\n      pattern: pathToRegexp_1(routepath, keys, {\n        end: exact,\n        strict: routepath === ''\n      }),\n    };\n    cache$1.set(cacheKey, regexp);\n  }\n\n  const m = regexp.pattern.exec(path);\n  if (!m) {\n    return null;\n  }\n\n  const params = Object.assign({}, parentParams);\n\n  for (let i = 1; i < m.length; i++) {\n    const key = regexp.keys[i - 1];\n    const prop = key.name;\n    const value = m[i];\n    if (value !== undefined || !hasOwnProperty.call(params, prop)) {\n      if (key.repeat) {\n        params[prop] = value ? value.split(key.delimiter).map(decodeParam) : [];\n      } else {\n        params[prop] = value ? decodeParam(value) : value;\n      }\n    }\n  }\n\n  return {\n    path: m[0],\n    keys: (parentKeys || []).concat(regexp.keys),\n    params,\n  };\n}\n\n/**\n * Universal Router (https://www.kriasoft.com/universal-router/)\n *\n * Copyright (c) 2015-present Kriasoft.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.txt file in the root directory of this source tree.\n */\n\n/**\n * Traverses the routes tree and matches its nodes to the given pathname from\n * the root down to the leaves. Each match consumes a part of the pathname and\n * the matching process continues for as long as there is a matching child\n * route for the remaining part of the pathname.\n *\n * The returned value is a lazily evaluated iterator.\n *\n * The leading \"/\" in a route path matters only for the root of the routes\n * tree (or if all parent routes are \"\"). In all other cases a leading \"/\" in\n * a child route path has no significance.\n *\n * The trailing \"/\" in a _route path_ matters only for the leaves of the\n * routes tree. A leaf route with a trailing \"/\" matches only a pathname that\n * also has a trailing \"/\".\n *\n * The trailing \"/\" in a route path does not affect matching of child routes\n * in any way.\n *\n * The trailing \"/\" in a _pathname_ generally does not matter (except for\n * the case of leaf nodes described above).\n *\n * The \"\" and \"/\" routes have special treatment:\n *  1. as a single route\n *     the \"\" and \"/\" routes match only the \"\" and \"/\" pathnames respectively\n *  2. as a parent in the routes tree\n *     the \"\" route matches any pathname without consuming any part of it\n *     the \"/\" route matches any absolute pathname consuming its leading \"/\"\n *  3. as a leaf in the routes tree\n *     the \"\" and \"/\" routes match only if the entire pathname is consumed by\n *         the parent routes chain. In this case \"\" and \"/\" are equivalent.\n *  4. several directly nested \"\" or \"/\" routes\n *     - directly nested \"\" or \"/\" routes are 'squashed' (i.e. nesting two\n *       \"/\" routes does not require a double \"/\" in the pathname to match)\n *     - if there are only \"\" in the parent routes chain, no part of the\n *       pathname is consumed, and the leading \"/\" in the child routes' paths\n *       remains significant\n *\n * Side effect:\n *   - the routes tree { path: '' } matches only the '' pathname\n *   - the routes tree { path: '', children: [ { path: '' } ] } matches any\n *     pathname (for the tree root)\n *\n * Prefix matching can be enabled also by `children: true`.\n */\nfunction matchRoute(route, pathname, ignoreLeadingSlash, parentKeys, parentParams) {\n  let match;\n  let childMatches;\n  let childIndex = 0;\n  let routepath = route.path || '';\n  if (routepath.charAt(0) === '/') {\n    if (ignoreLeadingSlash) {\n      routepath = routepath.substr(1);\n    }\n    ignoreLeadingSlash = true;\n  }\n\n  return {\n    next(routeToSkip) {\n      if (route === routeToSkip) {\n        return {done: true};\n      }\n\n      const children = route.__children = route.__children || route.children;\n\n      if (!match) {\n        match = matchPath(routepath, pathname, !children, parentKeys, parentParams);\n\n        if (match) {\n          return {\n            done: false,\n            value: {\n              route,\n              keys: match.keys,\n              params: match.params,\n              path: match.path\n            },\n          };\n        }\n      }\n\n      if (match && children) {\n        while (childIndex < children.length) {\n          if (!childMatches) {\n            const childRoute = children[childIndex];\n            childRoute.parent = route;\n\n            let matchedLength = match.path.length;\n            if (matchedLength > 0 && pathname.charAt(matchedLength) === '/') {\n              matchedLength += 1;\n            }\n\n            childMatches = matchRoute(\n              childRoute,\n              pathname.substr(matchedLength),\n              ignoreLeadingSlash,\n              match.keys,\n              match.params\n            );\n          }\n\n          const childMatch = childMatches.next(routeToSkip);\n          if (!childMatch.done) {\n            return {\n              done: false,\n              value: childMatch.value,\n            };\n          }\n\n          childMatches = null;\n          childIndex++;\n        }\n      }\n\n      return {done: true};\n    },\n  };\n}\n\n/**\n * Universal Router (https://www.kriasoft.com/universal-router/)\n *\n * Copyright (c) 2015-present Kriasoft.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.txt file in the root directory of this source tree.\n */\n\nfunction resolveRoute(context) {\n  if (isFunction(context.route.action)) {\n    return context.route.action(context);\n  }\n  return undefined;\n}\n\n/**\n * Universal Router (https://www.kriasoft.com/universal-router/)\n *\n * Copyright (c) 2015-present Kriasoft.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.txt file in the root directory of this source tree.\n */\n\nfunction isChildRoute(parentRoute, childRoute) {\n  let route = childRoute;\n  while (route) {\n    route = route.parent;\n    if (route === parentRoute) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction generateErrorMessage(currentContext) {\n  let errorMessage = `Path '${currentContext.pathname}' is not properly resolved due to an error.`;\n  const routePath = (currentContext.route || {}).path;\n  if (routePath) {\n    errorMessage += ` Resolution had failed on route: '${routePath}'`;\n  }\n  return errorMessage;\n}\n\nfunction updateChainForRoute(context, match) {\n  const {route, path} = match;\n\n  if (route && !route.__synthetic) {\n    const item = {path, route};\n    if (!context.chain) {\n      context.chain = [];\n    } else {\n      // Discard old items\n      if (route.parent) {\n        let i = context.chain.length;\n        while (i-- && context.chain[i].route && context.chain[i].route !== route.parent) {\n          context.chain.pop();\n        }\n      }\n    }\n    context.chain.push(item);\n  }\n}\n\n/**\n */\nclass Resolver {\n  constructor(routes, options = {}) {\n    if (Object(routes) !== routes) {\n      throw new TypeError('Invalid routes');\n    }\n\n    this.baseUrl = options.baseUrl || '';\n    this.errorHandler = options.errorHandler;\n    this.resolveRoute = options.resolveRoute || resolveRoute;\n    this.context = Object.assign({resolver: this}, options.context);\n    this.root = Array.isArray(routes) ? {path: '', __children: routes, parent: null, __synthetic: true} : routes;\n    this.root.parent = null;\n  }\n\n  /**\n   * Returns the current list of routes (as a shallow copy). Adding / removing\n   * routes to / from the returned array does not affect the routing config,\n   * but modifying the route objects does.\n   *\n   * @return {!Array<!Router.Route>}\n   */\n  getRoutes() {\n    return [...this.root.__children];\n  }\n\n  /**\n   * Sets the routing config (replacing the existing one).\n   *\n   * @param {!Array<!Router.Route>|!Router.Route} routes a single route or an array of those\n   *    (the array is shallow copied)\n   */\n  setRoutes(routes) {\n    ensureRoutes(routes);\n    const newRoutes = [...toArray(routes)];\n    this.root.__children = newRoutes;\n  }\n\n  /**\n   * Appends one or several routes to the routing config and returns the\n   * effective routing config after the operation.\n   *\n   * @param {!Array<!Router.Route>|!Router.Route} routes a single route or an array of those\n   *    (the array is shallow copied)\n   * @return {!Array<!Router.Route>}\n   * @protected\n   */\n  addRoutes(routes) {\n    ensureRoutes(routes);\n    this.root.__children.push(...toArray(routes));\n    return this.getRoutes();\n  }\n\n  /**\n   * Removes all existing routes from the routing config.\n   */\n  removeRoutes() {\n    this.setRoutes([]);\n  }\n\n  /**\n   * Asynchronously resolves the given pathname, i.e. finds all routes matching\n   * the pathname and tries resolving them one after another in the order they\n   * are listed in the routes config until the first non-null result.\n   *\n   * Returns a promise that is fulfilled with the return value of an object that consists of the first\n   * route handler result that returns something other than `null` or `undefined` and context used to get this result.\n   *\n   * If no route handlers return a non-null result, or if no route matches the\n   * given pathname the returned promise is rejected with a 'page not found'\n   * `Error`.\n   *\n   * @param {!string|!{pathname: !string}} pathnameOrContext the pathname to\n   *    resolve or a context object with a `pathname` property and other\n   *    properties to pass to the route resolver functions.\n   * @return {!Promise<any>}\n   */\n  resolve(pathnameOrContext) {\n    const context = Object.assign(\n      {},\n      this.context,\n      isString(pathnameOrContext) ? {pathname: pathnameOrContext} : pathnameOrContext\n    );\n    const match = matchRoute(\n      this.root,\n      this.__normalizePathname(context.pathname),\n      this.baseUrl\n    );\n    const resolve = this.resolveRoute;\n    let matches = null;\n    let nextMatches = null;\n    let currentContext = context;\n\n    function next(resume, parent = matches.value.route, prevResult) {\n      const routeToSkip = prevResult === null && matches.value.route;\n      matches = nextMatches || match.next(routeToSkip);\n      nextMatches = null;\n\n      if (!resume) {\n        if (matches.done || !isChildRoute(parent, matches.value.route)) {\n          nextMatches = matches;\n          return Promise.resolve(notFoundResult);\n        }\n      }\n\n      if (matches.done) {\n        return Promise.reject(getNotFoundError(context));\n      }\n\n      currentContext = Object.assign(\n        currentContext\n          ? {chain: (currentContext.chain ? currentContext.chain.slice(0) : [])}\n          : {},\n        context,\n        matches.value\n      );\n      updateChainForRoute(currentContext, matches.value);\n\n      return Promise.resolve(resolve(currentContext)).then(resolution => {\n        if (resolution !== null && resolution !== undefined && resolution !== notFoundResult) {\n          currentContext.result = resolution.result || resolution;\n          return currentContext;\n        }\n        return next(resume, parent, resolution);\n      });\n    }\n\n    context.next = next;\n\n    return Promise.resolve()\n      .then(() => next(true, this.root))\n      .catch((error) => {\n        const errorMessage = generateErrorMessage(currentContext);\n        if (!error) {\n          error = new Error(errorMessage);\n        } else {\n          console.warn(errorMessage);\n        }\n        error.context = error.context || currentContext;\n        // DOMException has its own code which is read-only\n        if (!(error instanceof DOMException)) {\n          error.code = error.code || 500;\n        }\n        if (this.errorHandler) {\n          currentContext.result = this.errorHandler(error);\n          return currentContext;\n        }\n        throw error;\n      });\n  }\n\n  /**\n   * URL constructor polyfill hook. Creates and returns an URL instance.\n   */\n  static __createUrl(url, base) {\n    return new URL(url, base);\n  }\n\n  /**\n   * If the baseUrl property is set, transforms the baseUrl and returns the full\n   * actual `base` string for using in the `new URL(path, base);` and for\n   * prepernding the paths with. The returned base ends with a trailing slash.\n   *\n   * Otherwise, returns empty string.\n   */\n  get __effectiveBaseUrl() {\n    return this.baseUrl\n      ? this.constructor.__createUrl(\n        this.baseUrl,\n        document.baseURI || document.URL\n      ).href.replace(/[^\\/]*$/, '')\n      : '';\n  }\n\n  /**\n   * If the baseUrl is set, matches the pathname with the router’s baseUrl,\n   * and returns the local pathname with the baseUrl stripped out.\n   *\n   * If the pathname does not match the baseUrl, returns undefined.\n   *\n   * If the `baseUrl` is not set, returns the unmodified pathname argument.\n   */\n  __normalizePathname(pathname) {\n    if (!this.baseUrl) {\n      // No base URL, no need to transform the pathname.\n      return pathname;\n    }\n\n    const base = this.__effectiveBaseUrl;\n    const normalizedUrl = this.constructor.__createUrl(pathname, base).href;\n    if (normalizedUrl.slice(0, base.length) === base) {\n      return normalizedUrl.slice(base.length);\n    }\n  }\n}\n\nResolver.pathToRegexp = pathToRegexp_1;\n\n/**\n * Universal Router (https://www.kriasoft.com/universal-router/)\n *\n * Copyright (c) 2015-present Kriasoft.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.txt file in the root directory of this source tree.\n */\n\nconst {pathToRegexp} = Resolver;\nconst cache = new Map();\n\nfunction cacheRoutes(routesByName, route, routes) {\n  const name = route.name || route.component;\n  if (name) {\n    if (routesByName.has(name)) {\n      routesByName.get(name).push(route);\n    } else {\n      routesByName.set(name, [route]);\n    }\n  }\n\n  if (Array.isArray(routes)) {\n    for (let i = 0; i < routes.length; i++) {\n      const childRoute = routes[i];\n      childRoute.parent = route;\n      cacheRoutes(routesByName, childRoute, childRoute.__children || childRoute.children);\n    }\n  }\n}\n\nfunction getRouteByName(routesByName, routeName) {\n  const routes = routesByName.get(routeName);\n  if (routes && routes.length > 1) {\n    throw new Error(\n      `Duplicate route with name \"${routeName}\".`\n      + ` Try seting unique 'name' route properties.`\n    );\n  }\n  return routes && routes[0];\n}\n\nfunction getRoutePath(route) {\n  let path = route.path;\n  path = Array.isArray(path) ? path[0] : path;\n  return path !== undefined ? path : '';\n}\n\nfunction generateUrls(router, options = {}) {\n  if (!(router instanceof Resolver)) {\n    throw new TypeError('An instance of Resolver is expected');\n  }\n\n  const routesByName = new Map();\n\n  return (routeName, params) => {\n    let route = getRouteByName(routesByName, routeName);\n    if (!route) {\n      routesByName.clear(); // clear cache\n      cacheRoutes(routesByName, router.root, router.root.__children);\n\n      route = getRouteByName(routesByName, routeName);\n      if (!route) {\n        throw new Error(`Route \"${routeName}\" not found`);\n      }\n    }\n\n    let regexp = cache.get(route.fullPath);\n    if (!regexp) {\n      let fullPath = getRoutePath(route);\n      let rt = route.parent;\n      while (rt) {\n        const path = getRoutePath(rt);\n        if (path) {\n          fullPath = path.replace(/\\/$/, '') + '/' + fullPath.replace(/^\\//, '');\n        }\n        rt = rt.parent;\n      }\n      const tokens = pathToRegexp.parse(fullPath);\n      const toPath = pathToRegexp.tokensToFunction(tokens);\n      const keys = Object.create(null);\n      for (let i = 0; i < tokens.length; i++) {\n        if (!isString(tokens[i])) {\n          keys[tokens[i].name] = true;\n        }\n      }\n      regexp = {toPath, keys};\n      cache.set(fullPath, regexp);\n      route.fullPath = fullPath;\n    }\n\n    let url = regexp.toPath(params, options) || '/';\n\n    if (options.stringifyQueryParams && params) {\n      const queryParams = {};\n      const keys = Object.keys(params);\n      for (let i = 0; i < keys.length; i++) {\n        const key = keys[i];\n        if (!regexp.keys[key]) {\n          queryParams[key] = params[key];\n        }\n      }\n      const query = options.stringifyQueryParams(queryParams);\n      if (query) {\n        url += query.charAt(0) === '?' ? query : `?${query}`;\n      }\n    }\n\n    return url;\n  };\n}\n\n/**\n * @typedef NavigationTrigger\n * @type {object}\n * @property {function()} activate\n * @property {function()} inactivate\n */\n\n/** @type {Array<NavigationTrigger>} */\nlet triggers = [];\n\nfunction setNavigationTriggers(newTriggers) {\n  triggers.forEach(trigger => trigger.inactivate());\n\n  newTriggers.forEach(trigger => trigger.activate());\n\n  triggers = newTriggers;\n}\n\nconst willAnimate = elem => {\n  const name = getComputedStyle(elem).getPropertyValue('animation-name');\n  return name && name !== 'none';\n};\n\nconst waitForAnimation = (elem, cb) => {\n  const listener = () => {\n    elem.removeEventListener('animationend', listener);\n    cb();\n  };\n  elem.addEventListener('animationend', listener);\n};\n\nfunction animate(elem, className) {\n  elem.classList.add(className);\n\n  return new Promise(resolve => {\n    if (willAnimate(elem)) {\n      const rect = elem.getBoundingClientRect();\n      const size = `height: ${rect.bottom - rect.top}px; width: ${rect.right - rect.left}px`;\n      elem.setAttribute('style', `position: absolute; ${size}`);\n      waitForAnimation(elem, () => {\n        elem.classList.remove(className);\n        elem.removeAttribute('style');\n        resolve();\n      });\n    } else {\n      elem.classList.remove(className);\n      resolve();\n    }\n  });\n}\n\nconst MAX_REDIRECT_COUNT = 256;\n\nfunction isResultNotEmpty(result) {\n  return result !== null && result !== undefined;\n}\n\nfunction copyContextWithoutNext(context) {\n  const copy = Object.assign({}, context);\n  delete copy.next;\n  return copy;\n}\n\nfunction createLocation({pathname = '', search = '', hash = '', chain = [], params = {}, redirectFrom, resolver}, route) {\n  const routes = chain.map(item => item.route);\n  return {\n    baseUrl: resolver && resolver.baseUrl || '',\n    pathname,\n    search,\n    hash,\n    routes,\n    route: route || routes.length && routes[routes.length - 1] || null,\n    params,\n    redirectFrom,\n    getUrl: (userParams = {}) => getPathnameForRouter(\n      Router.pathToRegexp.compile(\n        getMatchedPath(routes)\n      )(Object.assign({}, params, userParams)),\n      resolver\n    )\n  };\n}\n\nfunction createRedirect(context, pathname) {\n  const params = Object.assign({}, context.params);\n  return {\n    redirect: {\n      pathname,\n      from: context.pathname,\n      params\n    }\n  };\n}\n\nfunction renderElement(context, element) {\n  element.location = createLocation(context);\n  const index = context.chain.map(item => item.route).indexOf(context.route);\n  context.chain[index].element = element;\n  return element;\n}\n\nfunction runCallbackIfPossible(callback, args, thisArg) {\n  if (isFunction(callback)) {\n    return callback.apply(thisArg, args);\n  }\n}\n\nfunction amend(amendmentFunction, args, element) {\n  return amendmentResult => {\n    if (amendmentResult && (amendmentResult.cancel || amendmentResult.redirect)) {\n      return amendmentResult;\n    }\n\n    if (element) {\n      return runCallbackIfPossible(element[amendmentFunction], args, element);\n    }\n  };\n}\n\nfunction processNewChildren(newChildren, route) {\n  if (!Array.isArray(newChildren) && !isObject(newChildren)) {\n    throw new Error(\n      log(\n        `Incorrect \"children\" value for the route ${route.path}: expected array or object, but got ${newChildren}`\n      )\n    );\n  }\n\n  route.__children = [];\n  const childRoutes = toArray(newChildren);\n  for (let i = 0; i < childRoutes.length; i++) {\n    ensureRoute(childRoutes[i]);\n    route.__children.push(childRoutes[i]);\n  }\n}\n\nfunction removeDomNodes(nodes) {\n  if (nodes && nodes.length) {\n    const parent = nodes[0].parentNode;\n    for (let i = 0; i < nodes.length; i++) {\n      parent.removeChild(nodes[i]);\n    }\n  }\n}\n\nfunction getPathnameForRouter(pathname, router) {\n  const base = router.__effectiveBaseUrl;\n  return base\n    ? router.constructor.__createUrl(pathname.replace(/^\\//, ''), base).pathname\n    : pathname;\n}\n\nfunction getMatchedPath(chain) {\n  return chain.map(item => item.path).reduce((a, b) => {\n    if (b.length) {\n      return a.replace(/\\/$/, '') + '/' + b.replace(/^\\//, '');\n    }\n    return a;\n  }, '');\n}\n\n/**\n * A simple client-side router for single-page applications. It uses\n * express-style middleware and has a first-class support for Web Components and\n * lazy-loading. Works great in Polymer and non-Polymer apps.\n *\n * Use `new Router(outlet, options)` to create a new Router instance.\n *\n * * The `outlet` parameter is a reference to the DOM node to render\n *   the content into.\n *\n * * The `options` parameter is an optional object with options. The following\n *   keys are supported:\n *   * `baseUrl` — the initial value for [\n *     the `baseUrl` property\n *   ](#/classes/Router#property-baseUrl)\n *\n * The Router instance is automatically subscribed to navigation events\n * on `window`.\n *\n * See [Live Examples](#/classes/Router/demos/demo/index.html) for the detailed usage demo and code snippets.\n *\n * See also detailed API docs for the following methods, for the advanced usage:\n *\n * * [setOutlet](#/classes/Router#method-setOutlet) – should be used to configure the outlet.\n * * [setTriggers](#/classes/Router#method-setTriggers) – should be used to configure the navigation events.\n * * [setRoutes](#/classes/Router#method-setRoutes) – should be used to configure the routes.\n *\n * Only `setRoutes` has to be called manually, others are automatically invoked when creating a new instance.\n *\n * @extends Resolver\n * @demo demo/index.html\n * @summary JavaScript class that renders different DOM content depending on\n *    a given path. It can re-render when triggered or automatically on\n *    'popstate' and / or 'click' events.\n */\nclass Router extends Resolver {\n\n  /**\n   * Creates a new Router instance with a given outlet, and\n   * automatically subscribes it to navigation events on the `window`.\n   * Using a constructor argument or a setter for outlet is equivalent:\n   *\n   * ```\n   * const router = new Router();\n   * router.setOutlet(outlet);\n   * ```\n   * @param {?Node=} outlet\n   * @param {?RouterOptions=} options\n   */\n  constructor(outlet, options) {\n    const baseElement = document.head.querySelector('base');\n    const baseHref = baseElement && baseElement.getAttribute('href');\n    super([], Object.assign({\n      // Default options\n      baseUrl: baseHref && Resolver.__createUrl(baseHref, document.URL).pathname.replace(/[^\\/]*$/, '')\n    }, options));\n\n    this.resolveRoute = context => this.__resolveRoute(context);\n\n    const triggers = Router.NavigationTrigger;\n    Router.setTriggers.apply(Router, Object.keys(triggers).map(key => triggers[key]));\n\n    /**\n     * The base URL for all routes in the router instance. By default,\n     * if the base element exists in the `<head>`, vaadin-router\n     * takes the `<base href>` attribute value, resolves against current `document.URL`\n     * and gets the `pathname` from the result.\n     *\n     * @public\n     * @type {string}\n     */\n    this.baseUrl;\n\n    /**\n     * A promise that is settled after the current render cycle completes. If\n     * there is no render cycle in progress the promise is immediately settled\n     * with the last render cycle result.\n     *\n     * @public\n     * @type {!Promise<!RouterLocation>}\n     */\n    this.ready;\n    this.ready = Promise.resolve(outlet);\n\n    /**\n     * Contains read-only information about the current router location:\n     * pathname, active routes, parameters. See the\n     * [Location type declaration](#/classes/RouterLocation)\n     * for more details.\n     *\n     * @public\n     * @type {!RouterLocation}\n     */\n    this.location;\n    this.location = createLocation({resolver: this});\n\n    this.__lastStartedRenderId = 0;\n    this.__navigationEventHandler = this.__onNavigationEvent.bind(this);\n    this.setOutlet(outlet);\n    this.subscribe();\n    // Using WeakMap instead of WeakSet because WeakSet is not supported by IE11\n    this.__createdByRouter = new WeakMap();\n    this.__addedByRouter = new WeakMap();\n  }\n\n  __resolveRoute(context) {\n    const route = context.route;\n\n    let callbacks = Promise.resolve();\n\n    if (isFunction(route.children)) {\n      callbacks = callbacks\n        .then(() => route.children(copyContextWithoutNext(context)))\n        .then(children => {\n          // The route.children() callback might have re-written the\n          // route.children property instead of returning a value\n          if (!isResultNotEmpty(children) && !isFunction(route.children)) {\n            children = route.children;\n          }\n          processNewChildren(children, route);\n        });\n    }\n\n    const commands = {\n      redirect: path => createRedirect(context, path),\n      component: (component) => {\n        const element = document.createElement(component);\n        this.__createdByRouter.set(element, true);\n        return element;\n      }\n    };\n\n    return callbacks\n      .then(() => {\n        if (this.__isLatestRender(context)) {\n          return runCallbackIfPossible(route.action, [context, commands], route);\n        }\n      })\n      .then(result => {\n        if (isResultNotEmpty(result)) {\n          // Actions like `() => import('my-view.js')` are not expected to\n          // end the resolution, despite the result is not empty. Checking\n          // the result with a whitelist of values that end the resolution.\n          if (result instanceof HTMLElement ||\n              result.redirect ||\n              result === notFoundResult) {\n            return result;\n          }\n        }\n\n        if (isString(route.redirect)) {\n          return commands.redirect(route.redirect);\n        }\n\n        if (route.bundle) {\n          return loadBundle(route.bundle)\n            .then(() => {}, () => {\n              throw new Error(log(`Bundle not found: ${route.bundle}. Check if the file name is correct`));\n            });\n        }\n      })\n      .then(result => {\n        if (isResultNotEmpty(result)) {\n          return result;\n        }\n        if (isString(route.component)) {\n          return commands.component(route.component);\n        }\n      });\n  }\n\n  /**\n   * Sets the router outlet (the DOM node where the content for the current\n   * route is inserted). Any content pre-existing in the router outlet is\n   * removed at the end of each render pass.\n   *\n   * NOTE: this method is automatically invoked first time when creating a new Router instance.\n   *\n   * @param {?Node} outlet the DOM node where the content for the current route\n   *     is inserted.\n   */\n  setOutlet(outlet) {\n    if (outlet) {\n      this.__ensureOutlet(outlet);\n    }\n    this.__outlet = outlet;\n  }\n\n  /**\n   * Returns the current router outlet. The initial value is `undefined`.\n   *\n   * @return {?Node} the current router outlet (or `undefined`)\n   */\n  getOutlet() {\n    return this.__outlet;\n  }\n\n  /**\n   * Sets the routing config (replacing the existing one) and triggers a\n   * navigation event so that the router outlet is refreshed according to the\n   * current `window.location` and the new routing config.\n   *\n   * Each route object may have the following properties, listed here in the processing order:\n   * * `path` – the route path (relative to the parent route if any) in the\n   * [express.js syntax](https://expressjs.com/en/guide/routing.html#route-paths\").\n   *\n   * * `children` – an array of nested routes or a function that provides this\n   * array at the render time. The function can be synchronous or asynchronous:\n   * in the latter case the render is delayed until the returned promise is\n   * resolved. The `children` function is executed every time when this route is\n   * being rendered. This allows for dynamic route structures (e.g. backend-defined),\n   * but it might have a performance impact as well. In order to avoid calling\n   * the function on subsequent renders, you can override the `children` property\n   * of the route object and save the calculated array there\n   * (via `context.route.children = [ route1, route2, ...];`).\n   * Parent routes are fully resolved before resolving the children. Children\n   * 'path' values are relative to the parent ones.\n   *\n   * * `action` – the action that is executed before the route is resolved.\n   * The value for this property should be a function, accepting `context`\n   * and `commands` parameters described below. If present, this function is\n   * always invoked first, disregarding of the other properties' presence.\n   * The action can return a result directly or within a `Promise`, which\n   * resolves to the result. If the action result is an `HTMLElement` instance,\n   * a `commands.component(name)` result, a `commands.redirect(path)` result,\n   * or a `context.next()` result, the current route resolution is finished,\n   * and other route config properties are ignored.\n   * See also **Route Actions** section in [Live Examples](#/classes/Router/demos/demo/index.html).\n   *\n   * * `redirect` – other route's path to redirect to. Passes all route parameters to the redirect target.\n   * The target route should also be defined.\n   * See also **Redirects** section in [Live Examples](#/classes/Router/demos/demo/index.html).\n   *\n   * * `bundle` – string containing the path to `.js` or `.mjs` bundle to load before resolving the route,\n   * or the object with \"module\" and \"nomodule\" keys referring to different bundles.\n   * Each bundle is only loaded once. If \"module\" and \"nomodule\" are set, only one bundle is loaded,\n   * depending on whether the browser supports ES modules or not.\n   * The property is ignored when either an `action` returns the result or `redirect` property is present.\n   * Any error, e.g. 404 while loading bundle will cause route resolution to throw.\n   * See also **Code Splitting** section in [Live Examples](#/classes/Router/demos/demo/index.html).\n   *\n   * * `component` – the tag name of the Web Component to resolve the route to.\n   * The property is ignored when either an `action` returns the result or `redirect` property is present.\n   * If route contains the `component` property (or an action that return a component)\n   * and its child route also contains the `component` property, child route's component\n   * will be rendered as a light dom child of a parent component.\n   *\n   * * `name` – the string name of the route to use in the\n   * [`router.urlForName(name, params)`](#/classes/Router#method-urlForName)\n   * navigation helper method.\n   *\n   * For any route function (`action`, `children`) defined, the corresponding `route` object is available inside the callback\n   * through the `this` reference. If you need to access it, make sure you define the callback as a non-arrow function\n   * because arrow functions do not have their own `this` reference.\n   *\n   * `context` object that is passed to `action` function holds the following properties:\n   * * `context.pathname` – string with the pathname being resolved\n   *\n   * * `context.search` – search query string\n   *\n   * * `context.hash` – hash string\n   *\n   * * `context.params` – object with route parameters\n   *\n   * * `context.route` – object that holds the route that is currently being rendered.\n   *\n   * * `context.next()` – function for asynchronously getting the next route\n   * contents from the resolution chain (if any)\n   *\n   * `commands` object that is passed to `action` function has\n   * the following methods:\n   *\n   * * `commands.redirect(path)` – function that creates a redirect data\n   * for the path specified.\n   *\n   * * `commands.component(component)` – function that creates a new HTMLElement\n   * with current context. Note: the component created by this function is reused if visiting the same path twice in row.\n   *\n   *\n   * @param {!Array<!Route>|!Route} routes a single route or an array of those\n   * @param {?boolean} skipRender configure the router but skip rendering the\n   *     route corresponding to the current `window.location` values\n   *\n   * @return {!Promise<!Node>}\n   */\n  setRoutes(routes, skipRender = false) {\n    this.__previousContext = undefined;\n    this.__urlForName = undefined;\n    super.setRoutes(routes);\n    if (!skipRender) {\n      this.__onNavigationEvent();\n    }\n    return this.ready;\n  }\n\n  /**\n   * Asynchronously resolves the given pathname and renders the resolved route\n   * component into the router outlet. If no router outlet is set at the time of\n   * calling this method, or at the time when the route resolution is completed,\n   * a `TypeError` is thrown.\n   *\n   * Returns a promise that is fulfilled with the router outlet DOM Node after\n   * the route component is created and inserted into the router outlet, or\n   * rejected if no route matches the given path.\n   *\n   * If another render pass is started before the previous one is completed, the\n   * result of the previous render pass is ignored.\n   *\n   * @param {!string|!{pathname: !string, search: ?string, hash: ?string}} pathnameOrContext\n   *    the pathname to render or a context object with a `pathname` property,\n   *    optional `search` and `hash` properties, and other properties\n   *    to pass to the resolver.\n   * @param {boolean=} shouldUpdateHistory\n   *    update browser history with the rendered location\n   * @return {!Promise<!Node>}\n   */\n  render(pathnameOrContext, shouldUpdateHistory) {\n    const renderId = ++this.__lastStartedRenderId;\n    const context = Object.assign(\n      {\n        search: '',\n        hash: ''\n      },\n      isString(pathnameOrContext)\n        ? {pathname: pathnameOrContext}\n        : pathnameOrContext,\n      {\n        __renderId: renderId\n      }\n    );\n\n    // Find the first route that resolves to a non-empty result\n    this.ready = this.resolve(context)\n\n      // Process the result of this.resolve() and handle all special commands:\n      // (redirect / prevent / component). If the result is a 'component',\n      // then go deeper and build the entire chain of nested components matching\n      // the pathname. Also call all 'on before' callbacks along the way.\n      .then(context => this.__fullyResolveChain(context))\n\n      .then(context => {\n        if (this.__isLatestRender(context)) {\n          const previousContext = this.__previousContext;\n\n          // Check if the render was prevented and make an early return in that case\n          if (context === previousContext) {\n            // Replace the history with the previous context\n            // to make sure the URL stays the same.\n            this.__updateBrowserHistory(previousContext, true);\n            return this.location;\n          }\n\n          this.location = createLocation(context);\n\n          if (shouldUpdateHistory) {\n            // Replace only if first render redirects, so that we don’t leave\n            // the redirecting record in the history\n            this.__updateBrowserHistory(context, renderId === 1);\n          }\n\n          fireRouterEvent('location-changed', {router: this, location: this.location});\n\n          // Skip detaching/re-attaching there are no render changes\n          if (context.__skipAttach) {\n            this.__copyUnchangedElements(context, previousContext);\n            this.__previousContext = context;\n            return this.location;\n          }\n\n          this.__addAppearingContent(context, previousContext);\n          const animationDone = this.__animateIfNeeded(context);\n\n          this.__runOnAfterEnterCallbacks(context);\n          this.__runOnAfterLeaveCallbacks(context, previousContext);\n\n          return animationDone.then(() => {\n            if (this.__isLatestRender(context)) {\n              // If there is another render pass started after this one,\n              // the 'disappearing content' would be removed when the other\n              // render pass calls `this.__addAppearingContent()`\n              this.__removeDisappearingContent();\n\n              this.__previousContext = context;\n              return this.location;\n            }\n          });\n        }\n      })\n      .catch(error => {\n        if (renderId === this.__lastStartedRenderId) {\n          if (shouldUpdateHistory) {\n            this.__updateBrowserHistory(context);\n          }\n          removeDomNodes(this.__outlet && this.__outlet.children);\n          this.location = createLocation(Object.assign(context, {resolver: this}));\n          fireRouterEvent('error', Object.assign({router: this, error}, context));\n          throw error;\n        }\n      });\n    return this.ready;\n  }\n\n  // `topOfTheChainContextBeforeRedirects` is a context coming from Resolver.resolve().\n  // It would contain a 'redirect' route or the first 'component' route that\n  // matched the pathname. There might be more child 'component' routes to be\n  // resolved and added into the chain. This method would find and add them.\n  // `contextBeforeRedirects` is the context containing such a child component\n  // route. It's only necessary when this method is called recursively (otherwise\n  // it's the same as the 'top of the chain' context).\n  //\n  // Apart from building the chain of child components, this method would also\n  // handle 'redirect' routes, call 'onBefore' callbacks and handle 'prevent'\n  // and 'redirect' callback results.\n  __fullyResolveChain(topOfTheChainContextBeforeRedirects,\n    contextBeforeRedirects = topOfTheChainContextBeforeRedirects) {\n    return this.__findComponentContextAfterAllRedirects(contextBeforeRedirects)\n      // `contextAfterRedirects` is always a context with an `HTMLElement` result\n      // In other cases the promise gets rejected and .then() is not called\n      .then(contextAfterRedirects => {\n        const redirectsHappened = contextAfterRedirects !== contextBeforeRedirects;\n        const topOfTheChainContextAfterRedirects =\n          redirectsHappened ? contextAfterRedirects : topOfTheChainContextBeforeRedirects;\n\n        const matchedPath = getPathnameForRouter(\n          getMatchedPath(contextAfterRedirects.chain),\n          contextAfterRedirects.resolver\n        );\n        const isFound = (matchedPath === contextAfterRedirects.pathname);\n\n        // Recursive method to try matching more child and sibling routes\n        const findNextContextIfAny = (context, parent = context.route, prevResult) => {\n          return context.next(undefined, parent, prevResult).then(nextContext => {\n            if (nextContext === null || nextContext === notFoundResult) {\n              // Next context is not found in children, ...\n              if (isFound) {\n                // ...but original context is already fully matching - use it\n                return context;\n              } else if (parent.parent !== null) {\n                // ...and there is no full match yet - step up to check siblings\n                return findNextContextIfAny(context, parent.parent, nextContext);\n              } else {\n                return nextContext;\n              }\n            }\n\n            return nextContext;\n          });\n        };\n\n        return findNextContextIfAny(contextAfterRedirects).then(nextContext => {\n          if (nextContext === null || nextContext === notFoundResult) {\n            throw getNotFoundError(topOfTheChainContextAfterRedirects);\n          }\n\n          return nextContext\n          && nextContext !== notFoundResult\n          && nextContext !== contextAfterRedirects\n            ? this.__fullyResolveChain(topOfTheChainContextAfterRedirects, nextContext)\n            : this.__amendWithOnBeforeCallbacks(contextAfterRedirects);\n        });\n      });\n  }\n\n  __findComponentContextAfterAllRedirects(context) {\n    const result = context.result;\n    if (result instanceof HTMLElement) {\n      renderElement(context, result);\n      return Promise.resolve(context);\n    } else if (result.redirect) {\n      return this.__redirect(result.redirect, context.__redirectCount, context.__renderId)\n        .then(context => this.__findComponentContextAfterAllRedirects(context));\n    } else if (result instanceof Error) {\n      return Promise.reject(result);\n    } else {\n      return Promise.reject(\n        new Error(\n          log(\n            `Invalid route resolution result for path \"${context.pathname}\". ` +\n            `Expected redirect object or HTML element, but got: \"${logValue(result)}\". ` +\n            `Double check the action return value for the route.`\n          )\n        ));\n    }\n  }\n\n  __amendWithOnBeforeCallbacks(contextWithFullChain) {\n    return this.__runOnBeforeCallbacks(contextWithFullChain).then(amendedContext => {\n      if (amendedContext === this.__previousContext || amendedContext === contextWithFullChain) {\n        return amendedContext;\n      }\n      return this.__fullyResolveChain(amendedContext);\n    });\n  }\n\n  __runOnBeforeCallbacks(newContext) {\n    const previousContext = this.__previousContext || {};\n    const previousChain = previousContext.chain || [];\n    const newChain = newContext.chain;\n\n    let callbacks = Promise.resolve();\n    const prevent = () => ({cancel: true});\n    const redirect = (pathname) => createRedirect(newContext, pathname);\n\n    newContext.__divergedChainIndex = 0;\n    newContext.__skipAttach = false;\n    if (previousChain.length) {\n      for (let i = 0; i < Math.min(previousChain.length, newChain.length); i = ++newContext.__divergedChainIndex) {\n        if (previousChain[i].route !== newChain[i].route\n          || previousChain[i].path !== newChain[i].path && previousChain[i].element !== newChain[i].element\n          || !this.__isReusableElement(previousChain[i].element, newChain[i].element)) {\n          break;\n        }\n      }\n\n      // Skip re-attaching and notifications if element and chain do not change\n      newContext.__skipAttach =\n        // Same route chain\n        newChain.length === previousChain.length && newContext.__divergedChainIndex == newChain.length &&\n        // Same element\n        this.__isReusableElement(newContext.result, previousContext.result);\n\n      if (newContext.__skipAttach) {\n        // execute onBeforeLeave for changed segment element when skipping attach\n        for (let i = newChain.length - 1; i >= 0; i--) {\n          callbacks = this.__runOnBeforeLeaveCallbacks(callbacks, newContext, {prevent}, previousChain[i]);\n        }\n        // execute onBeforeEnter for changed segment element when skipping attach\n        for (let i = 0; i < newChain.length; i++) {\n          callbacks = this.__runOnBeforeEnterCallbacks(callbacks, newContext, {prevent, redirect}, newChain[i]);\n          previousChain[i].element.location = createLocation(newContext, previousChain[i].route);\n        }\n\n      } else {\n        // execute onBeforeLeave when NOT skipping attach\n        for (let i = previousChain.length - 1; i >= newContext.__divergedChainIndex; i--) {\n          callbacks = this.__runOnBeforeLeaveCallbacks(callbacks, newContext, {prevent}, previousChain[i]);\n        }\n      }\n    }\n    // execute onBeforeEnter when NOT skipping attach\n    if (!newContext.__skipAttach) {\n      for (let i = 0; i < newChain.length; i++) {\n        if (i < newContext.__divergedChainIndex) {\n          if (i < previousChain.length && previousChain[i].element) {\n            previousChain[i].element.location = createLocation(newContext, previousChain[i].route);\n          }\n        } else {\n          callbacks = this.__runOnBeforeEnterCallbacks(callbacks, newContext, {prevent, redirect}, newChain[i]);\n          if (newChain[i].element) {\n            newChain[i].element.location = createLocation(newContext, newChain[i].route);\n          }\n        }\n      }\n    }\n    return callbacks.then(amendmentResult => {\n      if (amendmentResult) {\n        if (amendmentResult.cancel) {\n          this.__previousContext.__renderId = newContext.__renderId;\n          return this.__previousContext;\n        }\n        if (amendmentResult.redirect) {\n          return this.__redirect(amendmentResult.redirect, newContext.__redirectCount, newContext.__renderId);\n        }\n      }\n      return newContext;\n    });\n  }\n\n  __runOnBeforeLeaveCallbacks(callbacks, newContext, commands, chainElement) {\n    const location = createLocation(newContext);\n    return callbacks.then(result => {\n      if (this.__isLatestRender(newContext)) {\n        const afterLeaveFunction = amend('onBeforeLeave', [location, commands, this], chainElement.element);\n        return afterLeaveFunction(result);\n      }\n    }).then(result => {\n      if (!(result || {}).redirect) {\n        return result;\n      }\n    });\n  }\n\n  __runOnBeforeEnterCallbacks(callbacks, newContext, commands, chainElement) {\n    const location = createLocation(newContext, chainElement.route);\n    return callbacks.then(result => {\n      if (this.__isLatestRender(newContext)) {\n        const beforeEnterFunction = amend('onBeforeEnter', [location, commands, this], chainElement.element);\n        return beforeEnterFunction(result);\n      }\n    });\n  }\n\n  __isReusableElement(element, otherElement) {\n    if (element && otherElement) {\n      return this.__createdByRouter.get(element) && this.__createdByRouter.get(otherElement)\n        ? element.localName === otherElement.localName\n        : element === otherElement;\n    }\n    return false;\n  }\n\n  __isLatestRender(context) {\n    return context.__renderId === this.__lastStartedRenderId;\n  }\n\n  __redirect(redirectData, counter, renderId) {\n    if (counter > MAX_REDIRECT_COUNT) {\n      throw new Error(log(`Too many redirects when rendering ${redirectData.from}`));\n    }\n\n    return this.resolve({\n      pathname: this.urlForPath(\n        redirectData.pathname,\n        redirectData.params\n      ),\n      redirectFrom: redirectData.from,\n      __redirectCount: (counter || 0) + 1,\n      __renderId: renderId\n    });\n  }\n\n  __ensureOutlet(outlet = this.__outlet) {\n    if (!(outlet instanceof Node)) {\n      throw new TypeError(log(`Expected router outlet to be a valid DOM Node (but got ${outlet})`));\n    }\n  }\n\n  __updateBrowserHistory({pathname, search = '', hash = ''}, replace) {\n    if (window.location.pathname !== pathname\n        || window.location.search !== search\n        || window.location.hash !== hash\n    ) {\n      const changeState = replace ? 'replaceState' : 'pushState';\n      window.history[changeState](null, document.title, pathname + search + hash);\n      window.dispatchEvent(new PopStateEvent('popstate', {state: 'vaadin-router-ignore'}));\n    }\n  }\n\n  __copyUnchangedElements(context, previousContext) {\n    // Find the deepest common parent between the last and the new component\n    // chains. Update references for the unchanged elements in the new chain\n    let deepestCommonParent = this.__outlet;\n    for (let i = 0; i < context.__divergedChainIndex; i++) {\n      const unchangedElement = previousContext && previousContext.chain[i].element;\n      if (unchangedElement) {\n        if (unchangedElement.parentNode === deepestCommonParent) {\n          context.chain[i].element = unchangedElement;\n          deepestCommonParent = unchangedElement;\n        } else {\n          break;\n        }\n      }\n    }\n    return deepestCommonParent;\n  }\n\n  __addAppearingContent(context, previousContext) {\n    this.__ensureOutlet();\n\n    // If the previous 'entering' animation has not completed yet,\n    // stop it and remove that content from the DOM before adding new one.\n    this.__removeAppearingContent();\n\n    // Copy reusable elements from the previousContext to current\n    const deepestCommonParent = this.__copyUnchangedElements(context, previousContext);\n\n    // Keep two lists of DOM elements:\n    //  - those that should be removed once the transition animation is over\n    //  - and those that should remain\n    this.__appearingContent = [];\n    this.__disappearingContent = Array\n      .from(deepestCommonParent.children)\n      .filter(\n        // Only remove layout content that was added by router\n        e => this.__addedByRouter.get(e) &&\n        // Do not remove the result element to avoid flickering\n        e !== context.result);\n\n    // Add new elements (starting after the deepest common parent) to the DOM.\n    // That way only the components that are actually different between the two\n    // locations are added to the DOM (and those that are common remain in the\n    // DOM without first removing and then adding them again).\n    let parentElement = deepestCommonParent;\n    for (let i = context.__divergedChainIndex; i < context.chain.length; i++) {\n      const elementToAdd = context.chain[i].element;\n      if (elementToAdd) {\n        parentElement.appendChild(elementToAdd);\n        this.__addedByRouter.set(elementToAdd, true);\n        if (parentElement === deepestCommonParent) {\n          this.__appearingContent.push(elementToAdd);\n        }\n        parentElement = elementToAdd;\n      }\n    }\n  }\n\n  __removeDisappearingContent() {\n    if (this.__disappearingContent) {\n      removeDomNodes(this.__disappearingContent);\n    }\n    this.__disappearingContent = null;\n    this.__appearingContent = null;\n  }\n\n  __removeAppearingContent() {\n    if (this.__disappearingContent && this.__appearingContent) {\n      removeDomNodes(this.__appearingContent);\n      this.__disappearingContent = null;\n      this.__appearingContent = null;\n    }\n  }\n\n  __runOnAfterLeaveCallbacks(currentContext, targetContext) {\n    if (!targetContext) {\n      return;\n    }\n\n    // REVERSE iteration: from Z to A\n    for (let i = targetContext.chain.length - 1; i >= currentContext.__divergedChainIndex; i--) {\n      if (!this.__isLatestRender(currentContext)) {\n        break;\n      }\n      const currentComponent = targetContext.chain[i].element;\n      if (!currentComponent) {\n        continue;\n      }\n      try {\n        const location = createLocation(currentContext);\n        runCallbackIfPossible(\n          currentComponent.onAfterLeave,\n          [location, {}, targetContext.resolver],\n          currentComponent);\n      } finally {\n        if (this.__disappearingContent.indexOf(currentComponent) > -1) {\n          removeDomNodes(currentComponent.children);\n        }\n      }\n    }\n  }\n\n  __runOnAfterEnterCallbacks(currentContext) {\n    // forward iteration: from A to Z\n    for (let i = currentContext.__divergedChainIndex; i < currentContext.chain.length; i++) {\n      if (!this.__isLatestRender(currentContext)) {\n        break;\n      }\n      const currentComponent = currentContext.chain[i].element || {};\n      const location = createLocation(currentContext, currentContext.chain[i].route);\n      runCallbackIfPossible(\n        currentComponent.onAfterEnter,\n        [location, {}, currentContext.resolver],\n        currentComponent);\n    }\n  }\n\n  __animateIfNeeded(context) {\n    const from = (this.__disappearingContent || [])[0];\n    const to = (this.__appearingContent || [])[0];\n    const promises = [];\n\n    const chain = context.chain;\n    let config;\n    for (let i = chain.length; i > 0; i--) {\n      if (chain[i - 1].route.animate) {\n        config = chain[i - 1].route.animate;\n        break;\n      }\n    }\n\n    if (from && to && config) {\n      const leave = isObject(config) && config.leave || 'leaving';\n      const enter = isObject(config) && config.enter || 'entering';\n      promises.push(animate(from, leave));\n      promises.push(animate(to, enter));\n    }\n\n    return Promise.all(promises).then(() => context);\n  }\n\n  /**\n   * Subscribes this instance to navigation events on the `window`.\n   *\n   * NOTE: beware of resource leaks. For as long as a router instance is\n   * subscribed to navigation events, it won't be garbage collected.\n   */\n  subscribe() {\n    window.addEventListener('vaadin-router-go', this.__navigationEventHandler);\n  }\n\n  /**\n   * Removes the subscription to navigation events created in the `subscribe()`\n   * method.\n   */\n  unsubscribe() {\n    window.removeEventListener('vaadin-router-go', this.__navigationEventHandler);\n  }\n\n  __onNavigationEvent(event) {\n    const {pathname, search, hash} = event ? event.detail : window.location;\n    if (isString(this.__normalizePathname(pathname))) {\n      if (event && event.preventDefault) {\n        event.preventDefault();\n      }\n      this.render({pathname, search, hash}, true);\n    }\n  }\n\n  /**\n   * Configures what triggers Router navigation events:\n   *  - `POPSTATE`: popstate events on the current `window`\n   *  - `CLICK`: click events on `<a>` links leading to the current page\n   *\n   * This method is invoked with the pre-configured values when creating a new Router instance.\n   * By default, both `POPSTATE` and `CLICK` are enabled. This setup is expected to cover most of the use cases.\n   *\n   * See the `router-config.js` for the default navigation triggers config. Based on it, you can\n   * create the own one and only import the triggers you need, instead of pulling in all the code,\n   * e.g. if you want to handle `click` differently.\n   *\n   * See also **Navigation Triggers** section in [Live Examples](#/classes/Router/demos/demo/index.html).\n   *\n   * @param {...NavigationTrigger} triggers\n   */\n  static setTriggers(...triggers) {\n    setNavigationTriggers(triggers);\n  }\n\n  /**\n   * Generates a URL for the route with the given name, optionally performing\n   * substitution of parameters.\n   *\n   * The route is searched in all the Router instances subscribed to\n   * navigation events.\n   *\n   * **Note:** For child route names, only array children are considered.\n   * It is not possible to generate URLs using a name for routes set with\n   * a children function.\n   *\n   * @function urlForName\n   * @param {!string} name the route name or the route’s `component` name.\n   * @param {Params=} params Optional object with route path parameters.\n   * Named parameters are passed by name (`params[name] = value`), unnamed\n   * parameters are passed by index (`params[index] = value`).\n   *\n   * @return {string}\n   */\n  urlForName(name, params) {\n    if (!this.__urlForName) {\n      this.__urlForName = generateUrls(this);\n    }\n    return getPathnameForRouter(\n      this.__urlForName(name, params),\n      this\n    );\n  }\n\n  /**\n   * Generates a URL for the given route path, optionally performing\n   * substitution of parameters.\n   *\n   * @param {!string} path string route path declared in [express.js syntax](https://expressjs.com/en/guide/routing.html#route-paths\").\n   * @param {Params=} params Optional object with route path parameters.\n   * Named parameters are passed by name (`params[name] = value`), unnamed\n   * parameters are passed by index (`params[index] = value`).\n   *\n   * @return {string}\n   */\n  urlForPath(path, params) {\n    return getPathnameForRouter(\n      Router.pathToRegexp.compile(path)(params),\n      this\n    );\n  }\n\n  /**\n   * Triggers navigation to a new path. Returns a boolean without waiting until\n   * the navigation is complete. Returns `true` if at least one `Router`\n   * has handled the navigation (was subscribed and had `baseUrl` matching\n   * the `path` argument), otherwise returns `false`.\n   *\n   * @param {!string|!{pathname: !string, search: (string|undefined), hash: (string|undefined)}} path\n   *   a new in-app path string, or an URL-like object with `pathname`\n   *   string property, and optional `search` and `hash` string properties.\n   * @return {boolean}\n   */\n  static go(path) {\n    const {pathname, search, hash} = isString(path)\n      ? this.__createUrl(path, 'http://a') // some base to omit origin\n      : path;\n    return fireRouterEvent('go', {pathname, search, hash});\n  }\n}\n\nconst DEV_MODE_CODE_REGEXP =\n  /\\/\\*[\\*!]\\s+vaadin-dev-mode:start([\\s\\S]*)vaadin-dev-mode:end\\s+\\*\\*\\//i;\n\nconst FlowClients = window.Vaadin && window.Vaadin.Flow && window.Vaadin.Flow.clients;\n\nfunction isMinified() {\n  function test() {\n    /** vaadin-dev-mode:start\n    return false;\n    vaadin-dev-mode:end **/\n    return true;\n  }\n  return uncommentAndRun(test);\n}\n\nfunction isDevelopmentMode() {\n  try {\n    if (isForcedDevelopmentMode()) {\n      return true;\n    }\n\n    if (!isLocalhost()) {\n      return false;\n    }\n\n    if (FlowClients) {\n      return !isFlowProductionMode();\n    }\n\n    return !isMinified();\n  } catch (e) {\n    // Some error in this code, assume production so no further actions will be taken\n    return false;\n  }\n}\n\nfunction isForcedDevelopmentMode() {\n  return localStorage.getItem(\"vaadin.developmentmode.force\");\n}\n\nfunction isLocalhost() {\n  return ([\"localhost\",\"127.0.0.1\"].indexOf(window.location.hostname) >= 0);\n}\n\nfunction isFlowProductionMode() {\n  if (FlowClients) {\n    const productionModeApps = Object.keys(FlowClients)\n      .map(key => FlowClients[key])\n      .filter(client => client.productionMode);\n    if (productionModeApps.length > 0) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction uncommentAndRun(callback, args) {\n  if (typeof callback !== 'function') {\n    return;\n  }\n\n  const match = DEV_MODE_CODE_REGEXP.exec(callback.toString());\n  if (match) {\n    try {\n      // requires CSP: script-src 'unsafe-eval'\n      callback = new Function(match[1]);\n    } catch (e) {\n      // eat the exception\n      console.log('vaadin-development-mode-detector: uncommentAndRun() failed', e);\n    }\n  }\n\n  return callback(args);\n}\n\n// A guard against polymer-modulizer removing the window.Vaadin\n// initialization above.\nwindow['Vaadin'] = window['Vaadin'] || {};\n\n/**\n * Inspects the source code of the given `callback` function for\n * specially-marked _commented_ code. If such commented code is found in the\n * callback source, uncomments and runs that code instead of the callback\n * itself. Otherwise runs the callback as is.\n *\n * The optional arguments are passed into the callback / uncommented code,\n * the result is returned.\n *\n * See the `isMinified()` function source code in this file for an example.\n *\n */\nconst runIfDevelopmentMode = function(callback, args) {\n  if (window.Vaadin.developmentMode) {\n    return uncommentAndRun(callback, args);\n  }\n};\n\nif (window.Vaadin.developmentMode === undefined) {\n  window.Vaadin.developmentMode = isDevelopmentMode();\n}\n\n/* This file is autogenerated from src/vaadin-usage-statistics.tpl.html */\n\nfunction maybeGatherAndSendStats() {\n  /** vaadin-dev-mode:start\n  (function () {\n'use strict';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n  return typeof obj;\n} : function (obj) {\n  return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n};\n\nvar classCallCheck = function (instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n};\n\nvar createClass = function () {\n  function defineProperties(target, props) {\n    for (var i = 0; i < props.length; i++) {\n      var descriptor = props[i];\n      descriptor.enumerable = descriptor.enumerable || false;\n      descriptor.configurable = true;\n      if (\"value\" in descriptor) descriptor.writable = true;\n      Object.defineProperty(target, descriptor.key, descriptor);\n    }\n  }\n\n  return function (Constructor, protoProps, staticProps) {\n    if (protoProps) defineProperties(Constructor.prototype, protoProps);\n    if (staticProps) defineProperties(Constructor, staticProps);\n    return Constructor;\n  };\n}();\n\nvar getPolymerVersion = function getPolymerVersion() {\n  return window.Polymer && window.Polymer.version;\n};\n\nvar StatisticsGatherer = function () {\n  function StatisticsGatherer(logger) {\n    classCallCheck(this, StatisticsGatherer);\n\n    this.now = new Date().getTime();\n    this.logger = logger;\n  }\n\n  createClass(StatisticsGatherer, [{\n    key: 'frameworkVersionDetectors',\n    value: function frameworkVersionDetectors() {\n      return {\n        'Flow': function Flow() {\n          if (window.Vaadin && window.Vaadin.Flow && window.Vaadin.Flow.clients) {\n            var flowVersions = Object.keys(window.Vaadin.Flow.clients).map(function (key) {\n              return window.Vaadin.Flow.clients[key];\n            }).filter(function (client) {\n              return client.getVersionInfo;\n            }).map(function (client) {\n              return client.getVersionInfo().flow;\n            });\n            if (flowVersions.length > 0) {\n              return flowVersions[0];\n            }\n          }\n        },\n        'Vaadin Framework': function VaadinFramework() {\n          if (window.vaadin && window.vaadin.clients) {\n            var frameworkVersions = Object.values(window.vaadin.clients).filter(function (client) {\n              return client.getVersionInfo;\n            }).map(function (client) {\n              return client.getVersionInfo().vaadinVersion;\n            });\n            if (frameworkVersions.length > 0) {\n              return frameworkVersions[0];\n            }\n          }\n        },\n        'AngularJs': function AngularJs() {\n          if (window.angular && window.angular.version && window.angular.version) {\n            return window.angular.version.full;\n          }\n        },\n        'Angular': function Angular() {\n          if (window.ng) {\n            var tags = document.querySelectorAll(\"[ng-version]\");\n            if (tags.length > 0) {\n              return tags[0].getAttribute(\"ng-version\");\n            }\n            return \"Unknown\";\n          }\n        },\n        'Backbone.js': function BackboneJs() {\n          if (window.Backbone) {\n            return window.Backbone.VERSION;\n          }\n        },\n        'React': function React() {\n          var reactSelector = '[data-reactroot], [data-reactid]';\n          if (!!document.querySelector(reactSelector)) {\n            // React does not publish the version by default\n            return \"unknown\";\n          }\n        },\n        'Ember': function Ember() {\n          if (window.Em && window.Em.VERSION) {\n            return window.Em.VERSION;\n          } else if (window.Ember && window.Ember.VERSION) {\n            return window.Ember.VERSION;\n          }\n        },\n        'jQuery': function (_jQuery) {\n          function jQuery() {\n            return _jQuery.apply(this, arguments);\n          }\n\n          jQuery.toString = function () {\n            return _jQuery.toString();\n          };\n\n          return jQuery;\n        }(function () {\n          if (typeof jQuery === 'function' && jQuery.prototype.jquery !== undefined) {\n            return jQuery.prototype.jquery;\n          }\n        }),\n        'Polymer': function Polymer() {\n          var version = getPolymerVersion();\n          if (version) {\n            return version;\n          }\n        },\n        'LitElement': function LitElement() {\n          var version = window.litElementVersions && window.litElementVersions[0];\n          if (version) {\n            return version;\n          }\n        },\n        'LitHtml': function LitHtml() {\n          var version = window.litHtmlVersions && window.litHtmlVersions[0];\n          if (version) {\n            return version;\n          }\n        },\n        'Vue.js': function VueJs() {\n          if (window.Vue) {\n            return window.Vue.version;\n          }\n        }\n      };\n    }\n  }, {\n    key: 'getUsedVaadinElements',\n    value: function getUsedVaadinElements(elements) {\n      var version = getPolymerVersion();\n      var elementClasses = void 0;\n      // NOTE: In case you edit the code here, YOU MUST UPDATE any statistics reporting code in Flow.\n      // Check all locations calling the method getEntries() in\n      // https://github.com/vaadin/flow/blob/master/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatistics.java#L106\n      // Currently it is only used by BootstrapHandler.\n      if (version && version.indexOf('2') === 0) {\n        // Polymer 2: components classes are stored in window.Vaadin\n        elementClasses = Object.keys(window.Vaadin).map(function (c) {\n          return window.Vaadin[c];\n        }).filter(function (c) {\n          return c.is;\n        });\n      } else {\n        // Polymer 3: components classes are stored in window.Vaadin.registrations\n        elementClasses = window.Vaadin.registrations || [];\n      }\n      elementClasses.forEach(function (klass) {\n        var version = klass.version ? klass.version : \"0.0.0\";\n        elements[klass.is] = { version: version };\n      });\n    }\n  }, {\n    key: 'getUsedVaadinThemes',\n    value: function getUsedVaadinThemes(themes) {\n      ['Lumo', 'Material'].forEach(function (themeName) {\n        var theme;\n        var version = getPolymerVersion();\n        if (version && version.indexOf('2') === 0) {\n          // Polymer 2: themes are stored in window.Vaadin\n          theme = window.Vaadin[themeName];\n        } else {\n          // Polymer 3: themes are stored in custom element registry\n          theme = customElements.get('vaadin-' + themeName.toLowerCase() + '-styles');\n        }\n        if (theme && theme.version) {\n          themes[themeName] = { version: theme.version };\n        }\n      });\n    }\n  }, {\n    key: 'getFrameworks',\n    value: function getFrameworks(frameworks) {\n      var detectors = this.frameworkVersionDetectors();\n      Object.keys(detectors).forEach(function (framework) {\n        var detector = detectors[framework];\n        try {\n          var version = detector();\n          if (version) {\n            frameworks[framework] = { version: version };\n          }\n        } catch (e) {}\n      });\n    }\n  }, {\n    key: 'gather',\n    value: function gather(storage) {\n      var storedStats = storage.read();\n      var gatheredStats = {};\n      var types = [\"elements\", \"frameworks\", \"themes\"];\n\n      types.forEach(function (type) {\n        gatheredStats[type] = {};\n        if (!storedStats[type]) {\n          storedStats[type] = {};\n        }\n      });\n\n      var previousStats = JSON.stringify(storedStats);\n\n      this.getUsedVaadinElements(gatheredStats.elements);\n      this.getFrameworks(gatheredStats.frameworks);\n      this.getUsedVaadinThemes(gatheredStats.themes);\n\n      var now = this.now;\n      types.forEach(function (type) {\n        var keys = Object.keys(gatheredStats[type]);\n        keys.forEach(function (key) {\n          if (!storedStats[type][key] || _typeof(storedStats[type][key]) != _typeof({})) {\n            storedStats[type][key] = { firstUsed: now };\n          }\n          // Discards any previously logged version number\n          storedStats[type][key].version = gatheredStats[type][key].version;\n          storedStats[type][key].lastUsed = now;\n        });\n      });\n\n      var newStats = JSON.stringify(storedStats);\n      storage.write(newStats);\n      if (newStats != previousStats && Object.keys(storedStats).length > 0) {\n        this.logger.debug(\"New stats: \" + newStats);\n      }\n    }\n  }]);\n  return StatisticsGatherer;\n}();\n\nvar StatisticsStorage = function () {\n  function StatisticsStorage(key) {\n    classCallCheck(this, StatisticsStorage);\n\n    this.key = key;\n  }\n\n  createClass(StatisticsStorage, [{\n    key: 'read',\n    value: function read() {\n      var localStorageStatsString = localStorage.getItem(this.key);\n      try {\n        return JSON.parse(localStorageStatsString ? localStorageStatsString : '{}');\n      } catch (e) {\n        return {};\n      }\n    }\n  }, {\n    key: 'write',\n    value: function write(data) {\n      localStorage.setItem(this.key, data);\n    }\n  }, {\n    key: 'clear',\n    value: function clear() {\n      localStorage.removeItem(this.key);\n    }\n  }, {\n    key: 'isEmpty',\n    value: function isEmpty() {\n      var storedStats = this.read();\n      var empty = true;\n      Object.keys(storedStats).forEach(function (key) {\n        if (Object.keys(storedStats[key]).length > 0) {\n          empty = false;\n        }\n      });\n\n      return empty;\n    }\n  }]);\n  return StatisticsStorage;\n}();\n\nvar StatisticsSender = function () {\n  function StatisticsSender(url, logger) {\n    classCallCheck(this, StatisticsSender);\n\n    this.url = url;\n    this.logger = logger;\n  }\n\n  createClass(StatisticsSender, [{\n    key: 'send',\n    value: function send(data, errorHandler) {\n      var logger = this.logger;\n\n      if (navigator.onLine === false) {\n        logger.debug(\"Offline, can't send\");\n        errorHandler();\n        return;\n      }\n      logger.debug(\"Sending data to \" + this.url);\n\n      var req = new XMLHttpRequest();\n      req.withCredentials = true;\n      req.addEventListener(\"load\", function () {\n        // Stats sent, nothing more to do\n        logger.debug(\"Response: \" + req.responseText);\n      });\n      req.addEventListener(\"error\", function () {\n        logger.debug(\"Send failed\");\n        errorHandler();\n      });\n      req.addEventListener(\"abort\", function () {\n        logger.debug(\"Send aborted\");\n        errorHandler();\n      });\n      req.open(\"POST\", this.url);\n      req.setRequestHeader(\"Content-Type\", \"application/json\");\n      req.send(data);\n    }\n  }]);\n  return StatisticsSender;\n}();\n\nvar StatisticsLogger = function () {\n  function StatisticsLogger(id) {\n    classCallCheck(this, StatisticsLogger);\n\n    this.id = id;\n  }\n\n  createClass(StatisticsLogger, [{\n    key: '_isDebug',\n    value: function _isDebug() {\n      return localStorage.getItem(\"vaadin.\" + this.id + \".debug\");\n    }\n  }, {\n    key: 'debug',\n    value: function debug(msg) {\n      if (this._isDebug()) {\n        console.info(this.id + \": \" + msg);\n      }\n    }\n  }]);\n  return StatisticsLogger;\n}();\n\nvar UsageStatistics = function () {\n  function UsageStatistics() {\n    classCallCheck(this, UsageStatistics);\n\n    this.now = new Date();\n    this.timeNow = this.now.getTime();\n    this.gatherDelay = 10; // Delay between loading this file and gathering stats\n    this.initialDelay = 24 * 60 * 60;\n\n    this.logger = new StatisticsLogger(\"statistics\");\n    this.storage = new StatisticsStorage(\"vaadin.statistics.basket\");\n    this.gatherer = new StatisticsGatherer(this.logger);\n    this.sender = new StatisticsSender(\"https://tools.vaadin.com/usage-stats/submit\", this.logger);\n  }\n\n  createClass(UsageStatistics, [{\n    key: 'maybeGatherAndSend',\n    value: function maybeGatherAndSend() {\n      var _this = this;\n\n      if (localStorage.getItem(UsageStatistics.optOutKey)) {\n        return;\n      }\n      this.gatherer.gather(this.storage);\n      setTimeout(function () {\n        _this.maybeSend();\n      }, this.gatherDelay * 1000);\n    }\n  }, {\n    key: 'lottery',\n    value: function lottery() {\n      return true;\n    }\n  }, {\n    key: 'currentMonth',\n    value: function currentMonth() {\n      return this.now.getYear() * 12 + this.now.getMonth();\n    }\n  }, {\n    key: 'maybeSend',\n    value: function maybeSend() {\n      var firstUse = Number(localStorage.getItem(UsageStatistics.firstUseKey));\n      var monthProcessed = Number(localStorage.getItem(UsageStatistics.monthProcessedKey));\n\n      if (!firstUse) {\n        // Use a grace period to avoid interfering with tests, incognito mode etc\n        firstUse = this.timeNow;\n        localStorage.setItem(UsageStatistics.firstUseKey, firstUse);\n      }\n\n      if (this.timeNow < firstUse + this.initialDelay * 1000) {\n        this.logger.debug(\"No statistics will be sent until the initial delay of \" + this.initialDelay + \"s has passed\");\n        return;\n      }\n      if (this.currentMonth() <= monthProcessed) {\n        this.logger.debug(\"This month has already been processed\");\n        return;\n      }\n      localStorage.setItem(UsageStatistics.monthProcessedKey, this.currentMonth());\n      // Use random sampling\n      if (this.lottery()) {\n        this.logger.debug(\"Congratulations, we have a winner!\");\n      } else {\n        this.logger.debug(\"Sorry, no stats from you this time\");\n        return;\n      }\n\n      this.send();\n    }\n  }, {\n    key: 'send',\n    value: function send() {\n      // Ensure we have the latest data\n      this.gatherer.gather(this.storage);\n\n      // Read, send and clean up\n      var data = this.storage.read();\n      data[\"firstUse\"] = Number(localStorage.getItem(UsageStatistics.firstUseKey));\n      data[\"usageStatisticsVersion\"] = UsageStatistics.version;\n      var info = 'This request contains usage statistics gathered from the application running in development mode. \\n\\nStatistics gathering is automatically disabled and excluded from production builds.\\n\\nFor details and to opt-out, see https://github.com/vaadin/vaadin-usage-statistics.\\n\\n\\n\\n';\n      var self = this;\n      this.sender.send(info + JSON.stringify(data), function () {\n        // Revert the 'month processed' flag\n        localStorage.setItem(UsageStatistics.monthProcessedKey, self.currentMonth() - 1);\n      });\n    }\n  }], [{\n    key: 'version',\n    get: function get$1() {\n      return '2.1.2';\n    }\n  }, {\n    key: 'firstUseKey',\n    get: function get$1() {\n      return 'vaadin.statistics.firstuse';\n    }\n  }, {\n    key: 'monthProcessedKey',\n    get: function get$1() {\n      return 'vaadin.statistics.monthProcessed';\n    }\n  }, {\n    key: 'optOutKey',\n    get: function get$1() {\n      return 'vaadin.statistics.optout';\n    }\n  }]);\n  return UsageStatistics;\n}();\n\ntry {\n  window.Vaadin = window.Vaadin || {};\n  window.Vaadin.usageStatsChecker = window.Vaadin.usageStatsChecker || new UsageStatistics();\n  window.Vaadin.usageStatsChecker.maybeGatherAndSend();\n} catch (e) {\n  // Intentionally ignored as this is not a problem in the app being developed\n}\n\n}());\n\n  vaadin-dev-mode:end **/\n}\n\nconst usageStatistics = function() {\n  if (typeof runIfDevelopmentMode === 'function') {\n    return runIfDevelopmentMode(maybeGatherAndSendStats);\n  }\n};\n\nwindow.Vaadin = window.Vaadin || {};\nwindow.Vaadin.registrations = window.Vaadin.registrations || [];\n\nwindow.Vaadin.registrations.push({\n  is: '@vaadin/router',\n  version: '1.7.4',\n});\n\nusageStatistics();\n\nRouter.NavigationTrigger = {POPSTATE, CLICK};\n\nexport { Resolver, Router };\n//# sourceMappingURL=vaadin-router.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n    /**\r\n     *\r\n     * @param name The public service name, e.g. app, auth, firestore, database\r\n     * @param instanceFactory Service factory responsible for creating the public interface\r\n     * @param type whether the service provided by the component is public or private\r\n     */\r\n    constructor(name, instanceFactory, type) {\r\n        this.name = name;\r\n        this.instanceFactory = instanceFactory;\r\n        this.type = type;\r\n        this.multipleInstances = false;\r\n        /**\r\n         * Properties to be added to the service namespace\r\n         */\r\n        this.serviceProps = {};\r\n        this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\r\n        this.onInstanceCreated = null;\r\n    }\r\n    setInstantiationMode(mode) {\r\n        this.instantiationMode = mode;\r\n        return this;\r\n    }\r\n    setMultipleInstances(multipleInstances) {\r\n        this.multipleInstances = multipleInstances;\r\n        return this;\r\n    }\r\n    setServiceProps(props) {\r\n        this.serviceProps = props;\r\n        return this;\r\n    }\r\n    setInstanceCreatedCallback(callback) {\r\n        this.onInstanceCreated = callback;\r\n        return this;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n    constructor(name, container) {\r\n        this.name = name;\r\n        this.container = container;\r\n        this.component = null;\r\n        this.instances = new Map();\r\n        this.instancesDeferred = new Map();\r\n        this.instancesOptions = new Map();\r\n        this.onInitCallbacks = new Map();\r\n    }\r\n    /**\r\n     * @param identifier A provider can provide mulitple instances of a service\r\n     * if this.component.multipleInstances is true.\r\n     */\r\n    get(identifier) {\r\n        // if multipleInstances is not supported, use the default name\r\n        const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n        if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n            const deferred = new Deferred();\r\n            this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n            if (this.isInitialized(normalizedIdentifier) ||\r\n                this.shouldAutoInitialize()) {\r\n                // initialize the service if it can be auto-initialized\r\n                try {\r\n                    const instance = this.getOrInitializeService({\r\n                        instanceIdentifier: normalizedIdentifier\r\n                    });\r\n                    if (instance) {\r\n                        deferred.resolve(instance);\r\n                    }\r\n                }\r\n                catch (e) {\r\n                    // when the instance factory throws an exception during get(), it should not cause\r\n                    // a fatal error. We just return the unresolved promise in this case.\r\n                }\r\n            }\r\n        }\r\n        return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n    }\r\n    getImmediate(options) {\r\n        var _a;\r\n        // if multipleInstances is not supported, use the default name\r\n        const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n        const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n        if (this.isInitialized(normalizedIdentifier) ||\r\n            this.shouldAutoInitialize()) {\r\n            try {\r\n                return this.getOrInitializeService({\r\n                    instanceIdentifier: normalizedIdentifier\r\n                });\r\n            }\r\n            catch (e) {\r\n                if (optional) {\r\n                    return null;\r\n                }\r\n                else {\r\n                    throw e;\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n            if (optional) {\r\n                return null;\r\n            }\r\n            else {\r\n                throw Error(`Service ${this.name} is not available`);\r\n            }\r\n        }\r\n    }\r\n    getComponent() {\r\n        return this.component;\r\n    }\r\n    setComponent(component) {\r\n        if (component.name !== this.name) {\r\n            throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n        }\r\n        if (this.component) {\r\n            throw Error(`Component for ${this.name} has already been provided`);\r\n        }\r\n        this.component = component;\r\n        // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n        if (!this.shouldAutoInitialize()) {\r\n            return;\r\n        }\r\n        // if the service is eager, initialize the default instance\r\n        if (isComponentEager(component)) {\r\n            try {\r\n                this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n            }\r\n            catch (e) {\r\n                // when the instance factory for an eager Component throws an exception during the eager\r\n                // initialization, it should not cause a fatal error.\r\n                // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n                // a fatal error in this case?\r\n            }\r\n        }\r\n        // Create service instances for the pending promises and resolve them\r\n        // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n        // and all promises with resolve with it regardless of the identifier.\r\n        for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n            const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n            try {\r\n                // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n                const instance = this.getOrInitializeService({\r\n                    instanceIdentifier: normalizedIdentifier\r\n                });\r\n                instanceDeferred.resolve(instance);\r\n            }\r\n            catch (e) {\r\n                // when the instance factory throws an exception, it should not cause\r\n                // a fatal error. We just leave the promise unresolved.\r\n            }\r\n        }\r\n    }\r\n    clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n        this.instancesDeferred.delete(identifier);\r\n        this.instancesOptions.delete(identifier);\r\n        this.instances.delete(identifier);\r\n    }\r\n    // app.delete() will call this method on every provider to delete the services\r\n    // TODO: should we mark the provider as deleted?\r\n    async delete() {\r\n        const services = Array.from(this.instances.values());\r\n        await Promise.all([\r\n            ...services\r\n                .filter(service => 'INTERNAL' in service) // legacy services\r\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n                .map(service => service.INTERNAL.delete()),\r\n            ...services\r\n                .filter(service => '_delete' in service) // modularized services\r\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n                .map(service => service._delete())\r\n        ]);\r\n    }\r\n    isComponentSet() {\r\n        return this.component != null;\r\n    }\r\n    isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n        return this.instances.has(identifier);\r\n    }\r\n    getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n        return this.instancesOptions.get(identifier) || {};\r\n    }\r\n    initialize(opts = {}) {\r\n        const { options = {} } = opts;\r\n        const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n        if (this.isInitialized(normalizedIdentifier)) {\r\n            throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n        }\r\n        if (!this.isComponentSet()) {\r\n            throw Error(`Component ${this.name} has not been registered yet`);\r\n        }\r\n        const instance = this.getOrInitializeService({\r\n            instanceIdentifier: normalizedIdentifier,\r\n            options\r\n        });\r\n        // resolve any pending promise waiting for the service instance\r\n        for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n            const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n            if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n                instanceDeferred.resolve(instance);\r\n            }\r\n        }\r\n        return instance;\r\n    }\r\n    /**\r\n     *\r\n     * @param callback - a function that will be invoked  after the provider has been initialized by calling provider.initialize().\r\n     * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n     *\r\n     * @param identifier An optional instance identifier\r\n     * @returns a function to unregister the callback\r\n     */\r\n    onInit(callback, identifier) {\r\n        var _a;\r\n        const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n        const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n        existingCallbacks.add(callback);\r\n        this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n        const existingInstance = this.instances.get(normalizedIdentifier);\r\n        if (existingInstance) {\r\n            callback(existingInstance, normalizedIdentifier);\r\n        }\r\n        return () => {\r\n            existingCallbacks.delete(callback);\r\n        };\r\n    }\r\n    /**\r\n     * Invoke onInit callbacks synchronously\r\n     * @param instance the service instance`\r\n     */\r\n    invokeOnInitCallbacks(instance, identifier) {\r\n        const callbacks = this.onInitCallbacks.get(identifier);\r\n        if (!callbacks) {\r\n            return;\r\n        }\r\n        for (const callback of callbacks) {\r\n            try {\r\n                callback(instance, identifier);\r\n            }\r\n            catch (_a) {\r\n                // ignore errors in the onInit callback\r\n            }\r\n        }\r\n    }\r\n    getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n        let instance = this.instances.get(instanceIdentifier);\r\n        if (!instance && this.component) {\r\n            instance = this.component.instanceFactory(this.container, {\r\n                instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n                options\r\n            });\r\n            this.instances.set(instanceIdentifier, instance);\r\n            this.instancesOptions.set(instanceIdentifier, options);\r\n            /**\r\n             * Invoke onInit listeners.\r\n             * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n             * while onInit listeners are registered by consumers of the provider.\r\n             */\r\n            this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n            /**\r\n             * Order is important\r\n             * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n             * makes `isInitialized()` return true.\r\n             */\r\n            if (this.component.onInstanceCreated) {\r\n                try {\r\n                    this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n                }\r\n                catch (_a) {\r\n                    // ignore errors in the onInstanceCreatedCallback\r\n                }\r\n            }\r\n        }\r\n        return instance || null;\r\n    }\r\n    normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n        if (this.component) {\r\n            return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n        }\r\n        else {\r\n            return identifier; // assume multiple instances are supported before the component is provided.\r\n        }\r\n    }\r\n    shouldAutoInitialize() {\r\n        return (!!this.component &&\r\n            this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\r\n    }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n    return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n    return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n    constructor(name) {\r\n        this.name = name;\r\n        this.providers = new Map();\r\n    }\r\n    /**\r\n     *\r\n     * @param component Component being added\r\n     * @param overwrite When a component with the same name has already been registered,\r\n     * if overwrite is true: overwrite the existing component with the new component and create a new\r\n     * provider with the new component. It can be useful in tests where you want to use different mocks\r\n     * for different tests.\r\n     * if overwrite is false: throw an exception\r\n     */\r\n    addComponent(component) {\r\n        const provider = this.getProvider(component.name);\r\n        if (provider.isComponentSet()) {\r\n            throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n        }\r\n        provider.setComponent(component);\r\n    }\r\n    addOrOverwriteComponent(component) {\r\n        const provider = this.getProvider(component.name);\r\n        if (provider.isComponentSet()) {\r\n            // delete the existing provider from the container, so we can register the new component\r\n            this.providers.delete(component.name);\r\n        }\r\n        this.addComponent(component);\r\n    }\r\n    /**\r\n     * getProvider provides a type safe interface where it can only be called with a field name\r\n     * present in NameServiceMapping interface.\r\n     *\r\n     * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n     * themselves.\r\n     */\r\n    getProvider(name) {\r\n        if (this.providers.has(name)) {\r\n            return this.providers.get(name);\r\n        }\r\n        // create a Provider for a service that hasn't registered with Firebase\r\n        const provider = new Provider(name, this);\r\n        this.providers.set(name, provider);\r\n        return provider;\r\n    }\r\n    getProviders() {\r\n        return Array.from(this.providers.values());\r\n    }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n    LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n    LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n    LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n    LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n    LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n    LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n    'debug': LogLevel.DEBUG,\r\n    'verbose': LogLevel.VERBOSE,\r\n    'info': LogLevel.INFO,\r\n    'warn': LogLevel.WARN,\r\n    'error': LogLevel.ERROR,\r\n    'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n    [LogLevel.DEBUG]: 'log',\r\n    [LogLevel.VERBOSE]: 'log',\r\n    [LogLevel.INFO]: 'info',\r\n    [LogLevel.WARN]: 'warn',\r\n    [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n    if (logType < instance.logLevel) {\r\n        return;\r\n    }\r\n    const now = new Date().toISOString();\r\n    const method = ConsoleMethod[logType];\r\n    if (method) {\r\n        console[method](`[${now}]  ${instance.name}:`, ...args);\r\n    }\r\n    else {\r\n        throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n    }\r\n};\r\nclass Logger {\r\n    /**\r\n     * Gives you an instance of a Logger to capture messages according to\r\n     * Firebase's logging scheme.\r\n     *\r\n     * @param name The name that the logs will be associated with\r\n     */\r\n    constructor(name) {\r\n        this.name = name;\r\n        /**\r\n         * The log level of the given Logger instance.\r\n         */\r\n        this._logLevel = defaultLogLevel;\r\n        /**\r\n         * The main (internal) log handler for the Logger instance.\r\n         * Can be set to a new function in internal package code but not by user.\r\n         */\r\n        this._logHandler = defaultLogHandler;\r\n        /**\r\n         * The optional, additional, user-defined log handler for the Logger instance.\r\n         */\r\n        this._userLogHandler = null;\r\n        /**\r\n         * Capture the current instance for later use\r\n         */\r\n        instances.push(this);\r\n    }\r\n    get logLevel() {\r\n        return this._logLevel;\r\n    }\r\n    set logLevel(val) {\r\n        if (!(val in LogLevel)) {\r\n            throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n        }\r\n        this._logLevel = val;\r\n    }\r\n    // Workaround for setter/getter having to be the same type.\r\n    setLogLevel(val) {\r\n        this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n    }\r\n    get logHandler() {\r\n        return this._logHandler;\r\n    }\r\n    set logHandler(val) {\r\n        if (typeof val !== 'function') {\r\n            throw new TypeError('Value assigned to `logHandler` must be a function');\r\n        }\r\n        this._logHandler = val;\r\n    }\r\n    get userLogHandler() {\r\n        return this._userLogHandler;\r\n    }\r\n    set userLogHandler(val) {\r\n        this._userLogHandler = val;\r\n    }\r\n    /**\r\n     * The functions below are all based on the `console` interface\r\n     */\r\n    debug(...args) {\r\n        this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n        this._logHandler(this, LogLevel.DEBUG, ...args);\r\n    }\r\n    log(...args) {\r\n        this._userLogHandler &&\r\n            this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n        this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n    }\r\n    info(...args) {\r\n        this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n        this._logHandler(this, LogLevel.INFO, ...args);\r\n    }\r\n    warn(...args) {\r\n        this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n        this._logHandler(this, LogLevel.WARN, ...args);\r\n    }\r\n    error(...args) {\r\n        this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n        this._logHandler(this, LogLevel.ERROR, ...args);\r\n    }\r\n}\r\nfunction setLogLevel(level) {\r\n    instances.forEach(inst => {\r\n        inst.setLogLevel(level);\r\n    });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n    for (const instance of instances) {\r\n        let customLogLevel = null;\r\n        if (options && options.level) {\r\n            customLogLevel = levelStringToEnum[options.level];\r\n        }\r\n        if (logCallback === null) {\r\n            instance.userLogHandler = null;\r\n        }\r\n        else {\r\n            instance.userLogHandler = (instance, level, ...args) => {\r\n                const message = args\r\n                    .map(arg => {\r\n                    if (arg == null) {\r\n                        return null;\r\n                    }\r\n                    else if (typeof arg === 'string') {\r\n                        return arg;\r\n                    }\r\n                    else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n                        return arg.toString();\r\n                    }\r\n                    else if (arg instanceof Error) {\r\n                        return arg.message;\r\n                    }\r\n                    else {\r\n                        try {\r\n                            return JSON.stringify(arg);\r\n                        }\r\n                        catch (ignored) {\r\n                            return null;\r\n                        }\r\n                    }\r\n                })\r\n                    .filter(arg => arg)\r\n                    .join(' ');\r\n                if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n                    logCallback({\r\n                        level: LogLevel[level].toLowerCase(),\r\n                        message,\r\n                        args,\r\n                        type: instance.name\r\n                    });\r\n                }\r\n            };\r\n        }\r\n    }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n    return (idbProxyableTypes ||\n        (idbProxyableTypes = [\n            IDBDatabase,\n            IDBObjectStore,\n            IDBIndex,\n            IDBCursor,\n            IDBTransaction,\n        ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n    return (cursorAdvanceMethods ||\n        (cursorAdvanceMethods = [\n            IDBCursor.prototype.advance,\n            IDBCursor.prototype.continue,\n            IDBCursor.prototype.continuePrimaryKey,\n        ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n    const promise = new Promise((resolve, reject) => {\n        const unlisten = () => {\n            request.removeEventListener('success', success);\n            request.removeEventListener('error', error);\n        };\n        const success = () => {\n            resolve(wrap(request.result));\n            unlisten();\n        };\n        const error = () => {\n            reject(request.error);\n            unlisten();\n        };\n        request.addEventListener('success', success);\n        request.addEventListener('error', error);\n    });\n    promise\n        .then((value) => {\n        // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n        // (see wrapFunction).\n        if (value instanceof IDBCursor) {\n            cursorRequestMap.set(value, request);\n        }\n        // Catching to avoid \"Uncaught Promise exceptions\"\n    })\n        .catch(() => { });\n    // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n    // is because we create many promises from a single IDBRequest.\n    reverseTransformCache.set(promise, request);\n    return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n    // Early bail if we've already created a done promise for this transaction.\n    if (transactionDoneMap.has(tx))\n        return;\n    const done = new Promise((resolve, reject) => {\n        const unlisten = () => {\n            tx.removeEventListener('complete', complete);\n            tx.removeEventListener('error', error);\n            tx.removeEventListener('abort', error);\n        };\n        const complete = () => {\n            resolve();\n            unlisten();\n        };\n        const error = () => {\n            reject(tx.error || new DOMException('AbortError', 'AbortError'));\n            unlisten();\n        };\n        tx.addEventListener('complete', complete);\n        tx.addEventListener('error', error);\n        tx.addEventListener('abort', error);\n    });\n    // Cache it for later retrieval.\n    transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n    get(target, prop, receiver) {\n        if (target instanceof IDBTransaction) {\n            // Special handling for transaction.done.\n            if (prop === 'done')\n                return transactionDoneMap.get(target);\n            // Polyfill for objectStoreNames because of Edge.\n            if (prop === 'objectStoreNames') {\n                return target.objectStoreNames || transactionStoreNamesMap.get(target);\n            }\n            // Make tx.store return the only store in the transaction, or undefined if there are many.\n            if (prop === 'store') {\n                return receiver.objectStoreNames[1]\n                    ? undefined\n                    : receiver.objectStore(receiver.objectStoreNames[0]);\n            }\n        }\n        // Else transform whatever we get back.\n        return wrap(target[prop]);\n    },\n    set(target, prop, value) {\n        target[prop] = value;\n        return true;\n    },\n    has(target, prop) {\n        if (target instanceof IDBTransaction &&\n            (prop === 'done' || prop === 'store')) {\n            return true;\n        }\n        return prop in target;\n    },\n};\nfunction replaceTraps(callback) {\n    idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n    // Due to expected object equality (which is enforced by the caching in `wrap`), we\n    // only create one new func per func.\n    // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n    if (func === IDBDatabase.prototype.transaction &&\n        !('objectStoreNames' in IDBTransaction.prototype)) {\n        return function (storeNames, ...args) {\n            const tx = func.call(unwrap(this), storeNames, ...args);\n            transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n            return wrap(tx);\n        };\n    }\n    // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n    // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n    // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n    // with real promises, so each advance methods returns a new promise for the cursor object, or\n    // undefined if the end of the cursor has been reached.\n    if (getCursorAdvanceMethods().includes(func)) {\n        return function (...args) {\n            // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n            // the original object.\n            func.apply(unwrap(this), args);\n            return wrap(cursorRequestMap.get(this));\n        };\n    }\n    return function (...args) {\n        // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n        // the original object.\n        return wrap(func.apply(unwrap(this), args));\n    };\n}\nfunction transformCachableValue(value) {\n    if (typeof value === 'function')\n        return wrapFunction(value);\n    // This doesn't return, it just creates a 'done' promise for the transaction,\n    // which is later returned for transaction.done (see idbObjectHandler).\n    if (value instanceof IDBTransaction)\n        cacheDonePromiseForTransaction(value);\n    if (instanceOfAny(value, getIdbProxyableTypes()))\n        return new Proxy(value, idbProxyTraps);\n    // Return the same value back if we're not going to transform it.\n    return value;\n}\nfunction wrap(value) {\n    // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n    // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n    if (value instanceof IDBRequest)\n        return promisifyRequest(value);\n    // If we've already transformed this value before, reuse the transformed value.\n    // This is faster, but it also provides object equality.\n    if (transformCache.has(value))\n        return transformCache.get(value);\n    const newValue = transformCachableValue(value);\n    // Not all types are transformed.\n    // These may be primitive types, so they can't be WeakMap keys.\n    if (newValue !== value) {\n        transformCache.set(value, newValue);\n        reverseTransformCache.set(newValue, value);\n    }\n    return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n    const request = indexedDB.open(name, version);\n    const openPromise = wrap(request);\n    if (upgrade) {\n        request.addEventListener('upgradeneeded', (event) => {\n            upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n        });\n    }\n    if (blocked) {\n        request.addEventListener('blocked', (event) => blocked(\n        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n        event.oldVersion, event.newVersion, event));\n    }\n    openPromise\n        .then((db) => {\n        if (terminated)\n            db.addEventListener('close', () => terminated());\n        if (blocking) {\n            db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n        }\n    })\n        .catch(() => { });\n    return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n    const request = indexedDB.deleteDatabase(name);\n    if (blocked) {\n        request.addEventListener('blocked', (event) => blocked(\n        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n        event.oldVersion, event));\n    }\n    return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n    if (!(target instanceof IDBDatabase &&\n        !(prop in target) &&\n        typeof prop === 'string')) {\n        return;\n    }\n    if (cachedMethods.get(prop))\n        return cachedMethods.get(prop);\n    const targetFuncName = prop.replace(/FromIndex$/, '');\n    const useIndex = prop !== targetFuncName;\n    const isWrite = writeMethods.includes(targetFuncName);\n    if (\n    // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n    !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n        !(isWrite || readMethods.includes(targetFuncName))) {\n        return;\n    }\n    const method = async function (storeName, ...args) {\n        // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n        const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n        let target = tx.store;\n        if (useIndex)\n            target = target.index(args.shift());\n        // Must reject if op rejects.\n        // If it's a write operation, must reject if tx.done rejects.\n        // Must reject with op rejection first.\n        // Must resolve with op value.\n        // Must handle both promises (no unhandled rejections)\n        return (await Promise.all([\n            target[targetFuncName](...args),\n            isWrite && tx.done,\n        ]))[0];\n    };\n    cachedMethods.set(prop, method);\n    return method;\n}\nreplaceTraps((oldTraps) => ({\n    ...oldTraps,\n    get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n    has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PlatformLoggerServiceImpl {\r\n    constructor(container) {\r\n        this.container = container;\r\n    }\r\n    // In initial implementation, this will be called by installations on\r\n    // auth token refresh, and installations will send this string.\r\n    getPlatformInfoString() {\r\n        const providers = this.container.getProviders();\r\n        // Loop through providers and get library/version pairs from any that are\r\n        // version components.\r\n        return providers\r\n            .map(provider => {\r\n            if (isVersionServiceProvider(provider)) {\r\n                const service = provider.getImmediate();\r\n                return `${service.library}/${service.version}`;\r\n            }\r\n            else {\r\n                return null;\r\n            }\r\n        })\r\n            .filter(logString => logString)\r\n            .join(' ');\r\n    }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n    const component = provider.getComponent();\r\n    return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* ComponentType.VERSION */;\r\n}\n\nconst name$o = \"@firebase/app\";\nconst version$1 = \"0.9.15\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/app');\n\nconst name$n = \"@firebase/app-compat\";\n\nconst name$m = \"@firebase/analytics-compat\";\n\nconst name$l = \"@firebase/analytics\";\n\nconst name$k = \"@firebase/app-check-compat\";\n\nconst name$j = \"@firebase/app-check\";\n\nconst name$i = \"@firebase/auth\";\n\nconst name$h = \"@firebase/auth-compat\";\n\nconst name$g = \"@firebase/database\";\n\nconst name$f = \"@firebase/database-compat\";\n\nconst name$e = \"@firebase/functions\";\n\nconst name$d = \"@firebase/functions-compat\";\n\nconst name$c = \"@firebase/installations\";\n\nconst name$b = \"@firebase/installations-compat\";\n\nconst name$a = \"@firebase/messaging\";\n\nconst name$9 = \"@firebase/messaging-compat\";\n\nconst name$8 = \"@firebase/performance\";\n\nconst name$7 = \"@firebase/performance-compat\";\n\nconst name$6 = \"@firebase/remote-config\";\n\nconst name$5 = \"@firebase/remote-config-compat\";\n\nconst name$4 = \"@firebase/storage\";\n\nconst name$3 = \"@firebase/storage-compat\";\n\nconst name$2 = \"@firebase/firestore\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"10.1.0\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n    [name$o]: 'fire-core',\r\n    [name$n]: 'fire-core-compat',\r\n    [name$l]: 'fire-analytics',\r\n    [name$m]: 'fire-analytics-compat',\r\n    [name$j]: 'fire-app-check',\r\n    [name$k]: 'fire-app-check-compat',\r\n    [name$i]: 'fire-auth',\r\n    [name$h]: 'fire-auth-compat',\r\n    [name$g]: 'fire-rtdb',\r\n    [name$f]: 'fire-rtdb-compat',\r\n    [name$e]: 'fire-fn',\r\n    [name$d]: 'fire-fn-compat',\r\n    [name$c]: 'fire-iid',\r\n    [name$b]: 'fire-iid-compat',\r\n    [name$a]: 'fire-fcm',\r\n    [name$9]: 'fire-fcm-compat',\r\n    [name$8]: 'fire-perf',\r\n    [name$7]: 'fire-perf-compat',\r\n    [name$6]: 'fire-rc',\r\n    [name$5]: 'fire-rc-compat',\r\n    [name$4]: 'fire-gcs',\r\n    [name$3]: 'fire-gcs-compat',\r\n    [name$2]: 'fire-fst',\r\n    [name$1]: 'fire-fst-compat',\r\n    'fire-js': 'fire-js',\r\n    [name]: 'fire-js-all'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n    try {\r\n        app.container.addComponent(component);\r\n    }\r\n    catch (e) {\r\n        logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n    }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n    app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n    const componentName = component.name;\r\n    if (_components.has(componentName)) {\r\n        logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n        return false;\r\n    }\r\n    _components.set(componentName, component);\r\n    // add the component to existing app instances\r\n    for (const app of _apps.values()) {\r\n        _addComponent(app, component);\r\n    }\r\n    return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n    const heartbeatController = app.container\r\n        .getProvider('heartbeat')\r\n        .getImmediate({ optional: true });\r\n    if (heartbeatController) {\r\n        void heartbeatController.triggerHeartbeat();\r\n    }\r\n    return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n    _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n    _components.clear();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n    [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n        'call initializeApp() first',\r\n    [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}\",\r\n    [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n    [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n    [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n    [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n        'Firebase App instance.',\r\n    [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n    [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n    [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n    [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n    [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseAppImpl {\r\n    constructor(options, config, container) {\r\n        this._isDeleted = false;\r\n        this._options = Object.assign({}, options);\r\n        this._config = Object.assign({}, config);\r\n        this._name = config.name;\r\n        this._automaticDataCollectionEnabled =\r\n            config.automaticDataCollectionEnabled;\r\n        this._container = container;\r\n        this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n    }\r\n    get automaticDataCollectionEnabled() {\r\n        this.checkDestroyed();\r\n        return this._automaticDataCollectionEnabled;\r\n    }\r\n    set automaticDataCollectionEnabled(val) {\r\n        this.checkDestroyed();\r\n        this._automaticDataCollectionEnabled = val;\r\n    }\r\n    get name() {\r\n        this.checkDestroyed();\r\n        return this._name;\r\n    }\r\n    get options() {\r\n        this.checkDestroyed();\r\n        return this._options;\r\n    }\r\n    get config() {\r\n        this.checkDestroyed();\r\n        return this._config;\r\n    }\r\n    get container() {\r\n        return this._container;\r\n    }\r\n    get isDeleted() {\r\n        return this._isDeleted;\r\n    }\r\n    set isDeleted(val) {\r\n        this._isDeleted = val;\r\n    }\r\n    /**\r\n     * This function will throw an Error if the App has already been deleted -\r\n     * use before performing API actions on the App.\r\n     */\r\n    checkDestroyed() {\r\n        if (this.isDeleted) {\r\n            throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\r\n        }\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n    let options = _options;\r\n    if (typeof rawConfig !== 'object') {\r\n        const name = rawConfig;\r\n        rawConfig = { name };\r\n    }\r\n    const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n    const name = config.name;\r\n    if (typeof name !== 'string' || !name) {\r\n        throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\r\n            appName: String(name)\r\n        });\r\n    }\r\n    options || (options = getDefaultAppConfig());\r\n    if (!options) {\r\n        throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\r\n    }\r\n    const existingApp = _apps.get(name);\r\n    if (existingApp) {\r\n        // return the existing app if options and config deep equal the ones in the existing app.\r\n        if (deepEqual(options, existingApp.options) &&\r\n            deepEqual(config, existingApp.config)) {\r\n            return existingApp;\r\n        }\r\n        else {\r\n            throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\r\n        }\r\n    }\r\n    const container = new ComponentContainer(name);\r\n    for (const component of _components.values()) {\r\n        container.addComponent(component);\r\n    }\r\n    const newApp = new FirebaseAppImpl(options, config, container);\r\n    _apps.set(name, newApp);\r\n    return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n *   provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n *   If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n    const app = _apps.get(name);\r\n    if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\r\n        return initializeApp();\r\n    }\r\n    if (!app) {\r\n        throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\r\n    }\r\n    return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n    return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n *   .then(function() {\r\n *     console.log(\"App deleted successfully\");\r\n *   })\r\n *   .catch(function(error) {\r\n *     console.log(\"Error deleting app:\", error);\r\n *   });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n    const name = app.name;\r\n    if (_apps.has(name)) {\r\n        _apps.delete(name);\r\n        await Promise.all(app.container\r\n            .getProviders()\r\n            .map(provider => provider.delete()));\r\n        app.isDeleted = true;\r\n    }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n    var _a;\r\n    // TODO: We can use this check to whitelist strings when/if we set up\r\n    // a good whitelist system.\r\n    let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n    if (variant) {\r\n        library += `-${variant}`;\r\n    }\r\n    const libraryMismatch = library.match(/\\s|\\//);\r\n    const versionMismatch = version.match(/\\s|\\//);\r\n    if (libraryMismatch || versionMismatch) {\r\n        const warning = [\r\n            `Unable to register library \"${library}\" with version \"${version}\":`\r\n        ];\r\n        if (libraryMismatch) {\r\n            warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n        }\r\n        if (libraryMismatch && versionMismatch) {\r\n            warning.push('and');\r\n        }\r\n        if (versionMismatch) {\r\n            warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n        }\r\n        logger.warn(warning.join(' '));\r\n        return;\r\n    }\r\n    _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n    if (logCallback !== null && typeof logCallback !== 'function') {\r\n        throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\r\n    }\r\n    setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n    setLogLevel$1(logLevel);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n    if (!dbPromise) {\r\n        dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n            upgrade: (db, oldVersion) => {\r\n                // We don't use 'break' in this switch statement, the fall-through\r\n                // behavior is what we want, because if there are multiple versions between\r\n                // the old version and the current version, we want ALL the migrations\r\n                // that correspond to those versions to run, not only the last one.\r\n                // eslint-disable-next-line default-case\r\n                switch (oldVersion) {\r\n                    case 0:\r\n                        db.createObjectStore(STORE_NAME);\r\n                }\r\n            }\r\n        }).catch(e => {\r\n            throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\r\n                originalErrorMessage: e.message\r\n            });\r\n        });\r\n    }\r\n    return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n    try {\r\n        const db = await getDbPromise();\r\n        const result = await db\r\n            .transaction(STORE_NAME)\r\n            .objectStore(STORE_NAME)\r\n            .get(computeKey(app));\r\n        return result;\r\n    }\r\n    catch (e) {\r\n        if (e instanceof FirebaseError) {\r\n            logger.warn(e.message);\r\n        }\r\n        else {\r\n            const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\r\n                originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n            });\r\n            logger.warn(idbGetError.message);\r\n        }\r\n    }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n    try {\r\n        const db = await getDbPromise();\r\n        const tx = db.transaction(STORE_NAME, 'readwrite');\r\n        const objectStore = tx.objectStore(STORE_NAME);\r\n        await objectStore.put(heartbeatObject, computeKey(app));\r\n        await tx.done;\r\n    }\r\n    catch (e) {\r\n        if (e instanceof FirebaseError) {\r\n            logger.warn(e.message);\r\n        }\r\n        else {\r\n            const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\r\n                originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n            });\r\n            logger.warn(idbGetError.message);\r\n        }\r\n    }\r\n}\r\nfunction computeKey(app) {\r\n    return `${app.name}!${app.options.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n    constructor(container) {\r\n        this.container = container;\r\n        /**\r\n         * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n         * the header string.\r\n         * Stores one record per date. This will be consolidated into the standard\r\n         * format of one record per user agent string before being sent as a header.\r\n         * Populated from indexedDB when the controller is instantiated and should\r\n         * be kept in sync with indexedDB.\r\n         * Leave public for easier testing.\r\n         */\r\n        this._heartbeatsCache = null;\r\n        const app = this.container.getProvider('app').getImmediate();\r\n        this._storage = new HeartbeatStorageImpl(app);\r\n        this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n            this._heartbeatsCache = result;\r\n            return result;\r\n        });\r\n    }\r\n    /**\r\n     * Called to report a heartbeat. The function will generate\r\n     * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n     * to IndexedDB.\r\n     * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n     * already logged, subsequent calls to this function in the same day will be ignored.\r\n     */\r\n    async triggerHeartbeat() {\r\n        const platformLogger = this.container\r\n            .getProvider('platform-logger')\r\n            .getImmediate();\r\n        // This is the \"Firebase user agent\" string from the platform logger\r\n        // service, not the browser user agent.\r\n        const agent = platformLogger.getPlatformInfoString();\r\n        const date = getUTCDateString();\r\n        if (this._heartbeatsCache === null) {\r\n            this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n        }\r\n        // Do not store a heartbeat if one is already stored for this day\r\n        // or if a header has already been sent today.\r\n        if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n            this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n            return;\r\n        }\r\n        else {\r\n            // There is no entry for this date. Create one.\r\n            this._heartbeatsCache.heartbeats.push({ date, agent });\r\n        }\r\n        // Remove entries older than 30 days.\r\n        this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n            const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n            const now = Date.now();\r\n            return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n        });\r\n        return this._storage.overwrite(this._heartbeatsCache);\r\n    }\r\n    /**\r\n     * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n     * It also clears all heartbeats from memory as well as in IndexedDB.\r\n     *\r\n     * NOTE: Consuming product SDKs should not send the header if this method\r\n     * returns an empty string.\r\n     */\r\n    async getHeartbeatsHeader() {\r\n        if (this._heartbeatsCache === null) {\r\n            await this._heartbeatsCachePromise;\r\n        }\r\n        // If it's still null or the array is empty, there is no data to send.\r\n        if (this._heartbeatsCache === null ||\r\n            this._heartbeatsCache.heartbeats.length === 0) {\r\n            return '';\r\n        }\r\n        const date = getUTCDateString();\r\n        // Extract as many heartbeats from the cache as will fit under the size limit.\r\n        const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n        const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n        // Store last sent date to prevent another being logged/sent for the same day.\r\n        this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n        if (unsentEntries.length > 0) {\r\n            // Store any unsent entries if they exist.\r\n            this._heartbeatsCache.heartbeats = unsentEntries;\r\n            // This seems more likely than emptying the array (below) to lead to some odd state\r\n            // since the cache isn't empty and this will be called again on the next request,\r\n            // and is probably safest if we await it.\r\n            await this._storage.overwrite(this._heartbeatsCache);\r\n        }\r\n        else {\r\n            this._heartbeatsCache.heartbeats = [];\r\n            // Do not wait for this, to reduce latency.\r\n            void this._storage.overwrite(this._heartbeatsCache);\r\n        }\r\n        return headerString;\r\n    }\r\n}\r\nfunction getUTCDateString() {\r\n    const today = new Date();\r\n    // Returns date format 'YYYY-MM-DD'\r\n    return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n    // Heartbeats grouped by user agent in the standard format to be sent in\r\n    // the header.\r\n    const heartbeatsToSend = [];\r\n    // Single date format heartbeats that are not sent.\r\n    let unsentEntries = heartbeatsCache.slice();\r\n    for (const singleDateHeartbeat of heartbeatsCache) {\r\n        // Look for an existing entry with the same user agent.\r\n        const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n        if (!heartbeatEntry) {\r\n            // If no entry for this user agent exists, create one.\r\n            heartbeatsToSend.push({\r\n                agent: singleDateHeartbeat.agent,\r\n                dates: [singleDateHeartbeat.date]\r\n            });\r\n            if (countBytes(heartbeatsToSend) > maxSize) {\r\n                // If the header would exceed max size, remove the added heartbeat\r\n                // entry and stop adding to the header.\r\n                heartbeatsToSend.pop();\r\n                break;\r\n            }\r\n        }\r\n        else {\r\n            heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n            // If the header would exceed max size, remove the added date\r\n            // and stop adding to the header.\r\n            if (countBytes(heartbeatsToSend) > maxSize) {\r\n                heartbeatEntry.dates.pop();\r\n                break;\r\n            }\r\n        }\r\n        // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n        // quota and the loop breaks early.)\r\n        unsentEntries = unsentEntries.slice(1);\r\n    }\r\n    return {\r\n        heartbeatsToSend,\r\n        unsentEntries\r\n    };\r\n}\r\nclass HeartbeatStorageImpl {\r\n    constructor(app) {\r\n        this.app = app;\r\n        this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n    }\r\n    async runIndexedDBEnvironmentCheck() {\r\n        if (!isIndexedDBAvailable()) {\r\n            return false;\r\n        }\r\n        else {\r\n            return validateIndexedDBOpenable()\r\n                .then(() => true)\r\n                .catch(() => false);\r\n        }\r\n    }\r\n    /**\r\n     * Read all heartbeats.\r\n     */\r\n    async read() {\r\n        const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n        if (!canUseIndexedDB) {\r\n            return { heartbeats: [] };\r\n        }\r\n        else {\r\n            const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n            return idbHeartbeatObject || { heartbeats: [] };\r\n        }\r\n    }\r\n    // overwrite the storage with the provided heartbeats\r\n    async overwrite(heartbeatsObject) {\r\n        var _a;\r\n        const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n        if (!canUseIndexedDB) {\r\n            return;\r\n        }\r\n        else {\r\n            const existingHeartbeatsObject = await this.read();\r\n            return writeHeartbeatsToIndexedDB(this.app, {\r\n                lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n                heartbeats: heartbeatsObject.heartbeats\r\n            });\r\n        }\r\n    }\r\n    // add heartbeats\r\n    async add(heartbeatsObject) {\r\n        var _a;\r\n        const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n        if (!canUseIndexedDB) {\r\n            return;\r\n        }\r\n        else {\r\n            const existingHeartbeatsObject = await this.read();\r\n            return writeHeartbeatsToIndexedDB(this.app, {\r\n                lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n                heartbeats: [\r\n                    ...existingHeartbeatsObject.heartbeats,\r\n                    ...heartbeatsObject.heartbeats\r\n                ]\r\n            });\r\n        }\r\n    }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n    // base64 has a restricted set of characters, all of which should be 1 byte.\r\n    return base64urlEncodeWithoutPadding(\r\n    // heartbeatsCache wrapper properties\r\n    JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerCoreComponents(variant) {\r\n    _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n    _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n    // Register `app` package.\r\n    registerVersion(name$o, version$1, variant);\r\n    // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n    registerVersion(name$o, version$1, 'esm2017');\r\n    // Register platform SDK identifier (no version).\r\n    registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _registerComponent, _removeServiceInstance, deleteApp, getApp, getApps, initializeApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","import { ErrorFactory, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, deepEqual, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';\nimport { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';\nimport { __rest } from 'tslib';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An enum of factors that may be used for multifactor authentication.\r\n *\r\n * @public\r\n */\r\nconst FactorId = {\r\n    /** Phone as second factor */\r\n    PHONE: 'phone',\r\n    TOTP: 'totp'\r\n};\r\n/**\r\n * Enumeration of supported providers.\r\n *\r\n * @public\r\n */\r\nconst ProviderId = {\r\n    /** Facebook provider ID */\r\n    FACEBOOK: 'facebook.com',\r\n    /** GitHub provider ID */\r\n    GITHUB: 'github.com',\r\n    /** Google provider ID */\r\n    GOOGLE: 'google.com',\r\n    /** Password provider */\r\n    PASSWORD: 'password',\r\n    /** Phone provider */\r\n    PHONE: 'phone',\r\n    /** Twitter provider ID */\r\n    TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported sign-in methods.\r\n *\r\n * @public\r\n */\r\nconst SignInMethod = {\r\n    /** Email link sign in method */\r\n    EMAIL_LINK: 'emailLink',\r\n    /** Email/password sign in method */\r\n    EMAIL_PASSWORD: 'password',\r\n    /** Facebook sign in method */\r\n    FACEBOOK: 'facebook.com',\r\n    /** GitHub sign in method */\r\n    GITHUB: 'github.com',\r\n    /** Google sign in method */\r\n    GOOGLE: 'google.com',\r\n    /** Phone sign in method */\r\n    PHONE: 'phone',\r\n    /** Twitter sign in method */\r\n    TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported operation types.\r\n *\r\n * @public\r\n */\r\nconst OperationType = {\r\n    /** Operation involving linking an additional provider to an already signed-in user. */\r\n    LINK: 'link',\r\n    /** Operation involving using a provider to reauthenticate an already signed-in user. */\r\n    REAUTHENTICATE: 'reauthenticate',\r\n    /** Operation involving signing in a user. */\r\n    SIGN_IN: 'signIn'\r\n};\r\n/**\r\n * An enumeration of the possible email action types.\r\n *\r\n * @public\r\n */\r\nconst ActionCodeOperation = {\r\n    /** The email link sign-in action. */\r\n    EMAIL_SIGNIN: 'EMAIL_SIGNIN',\r\n    /** The password reset action. */\r\n    PASSWORD_RESET: 'PASSWORD_RESET',\r\n    /** The email revocation action. */\r\n    RECOVER_EMAIL: 'RECOVER_EMAIL',\r\n    /** The revert second factor addition email action. */\r\n    REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\r\n    /** The revert second factor addition email action. */\r\n    VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\r\n    /** The email verification action. */\r\n    VERIFY_EMAIL: 'VERIFY_EMAIL'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _debugErrorMap() {\r\n    return {\r\n        [\"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',\r\n        [\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */]: '',\r\n        [\"app-not-authorized\" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: \"This app, identified by the domain where it's hosted, is not \" +\r\n            'authorized to use Firebase Authentication with the provided API key. ' +\r\n            'Review your key configuration in the Google API console.',\r\n        [\"app-not-installed\" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +\r\n            'Android package name or iOS bundle ID) provided is not installed on ' +\r\n            'this device.',\r\n        [\"captcha-check-failed\" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +\r\n            'already used or the domain associated with it does not match the list ' +\r\n            'of whitelisted domains.',\r\n        [\"code-expired\" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +\r\n            'again.',\r\n        [\"cordova-not-ready\" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',\r\n        [\"cors-unsupported\" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',\r\n        [\"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',\r\n        [\"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',\r\n        [\"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +\r\n            'again before retrying this request.',\r\n        [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n            'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n            'starting any other Firebase SDK.',\r\n        [\"dynamic-link-not-activated\" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\r\n            'conditions.',\r\n        [\"email-change-needs-verification\" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',\r\n        [\"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',\r\n        [\"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +\r\n            'no longer be configured to use the emulator. Try calling ' +\r\n            '\"connectAuthEmulator()\" sooner.',\r\n        [\"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',\r\n        [\"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',\r\n        [\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',\r\n        [\"invalid-app-credential\" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +\r\n            ' The reCAPTCHA token response is either invalid or expired.',\r\n        [\"invalid-app-id\" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',\r\n        [\"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */]: \"This user's credential isn't valid for this project. This can happen \" +\r\n            \"if the user's token has been tampered with, or if the user isn't for \" +\r\n            'the project associated with this API key.',\r\n        [\"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n        [\"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +\r\n            'invalid. Please resend the verification code sms and be sure to use the ' +\r\n            'verification code provided by the user.',\r\n        [\"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',\r\n        [\"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\r\n            'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\r\n            'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\r\n            'cordova-plugin-customurlscheme.',\r\n        [\"invalid-custom-token\" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',\r\n        [\"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',\r\n        [\"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',\r\n        [\"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',\r\n        [\"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',\r\n        [\"invalid-cert-hash\" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',\r\n        [\"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */]: 'The supplied auth credential is malformed or has expired.',\r\n        [\"invalid-message-payload\" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +\r\n            'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n        [\"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',\r\n        [\"invalid-oauth-provider\" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +\r\n            'only supports OAuth providers.',\r\n        [\"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +\r\n            'specified API key.',\r\n        [\"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +\r\n            'project. Edit the list of authorized domains from the Firebase console.',\r\n        [\"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +\r\n            'expired, or has already been used.',\r\n        [\"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',\r\n        [\"invalid-persistence-type\" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',\r\n        [\"invalid-phone-number\" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +\r\n            'phone number in a format that can be parsed into E.164 format. E.164 ' +\r\n            'phone numbers are written in the format [+][country code][subscriber ' +\r\n            'number including area code].',\r\n        [\"invalid-provider-id\" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',\r\n        [\"invalid-recipient-email\" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +\r\n            'recipient email address is invalid.',\r\n        [\"invalid-sender\" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +\r\n            'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n        [\"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',\r\n        [\"invalid-tenant-id\" /* AuthErrorCode.INVALID_TENANT_ID */]: \"The Auth instance's tenant ID is invalid.\",\r\n        [\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',\r\n        [\"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */]: 'An Android Package Name must be provided if the Android App is required to be installed.',\r\n        [\"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\r\n            'by following the instructions in the Firebase console.',\r\n        [\"missing-app-credential\" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +\r\n            'assertion. A reCAPTCHA response token needs to be provided.',\r\n        [\"missing-verification-code\" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',\r\n        [\"missing-continue-uri\" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',\r\n        [\"missing-iframe-start\" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',\r\n        [\"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',\r\n        [\"missing-or-invalid-nonce\" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +\r\n            'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\r\n            'in the ID token payload.',\r\n        [\"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */]: 'A non-empty password must be provided',\r\n        [\"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',\r\n        [\"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',\r\n        [\"missing-phone-number\" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',\r\n        [\"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',\r\n        [\"app-deleted\" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',\r\n        [\"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',\r\n        [\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',\r\n        [\"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +\r\n            'sign-in credentials. Sign in using a provider associated with this ' +\r\n            'email address.',\r\n        [\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\r\n        [\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n        [\"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',\r\n        [\"null-user\" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +\r\n            'requires a non-null user object.',\r\n        [\"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +\r\n            'Enable it in the Firebase console, under the sign-in method tab of the ' +\r\n            'Auth section.',\r\n        [\"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +\r\n            'running on. \"location.protocol\" must be http, https or chrome-extension' +\r\n            ' and web storage must be enabled.',\r\n        [\"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\r\n        [\"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',\r\n        [\"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',\r\n        [\"quota-exceeded\" /* AuthErrorCode.QUOTA_EXCEEDED */]: \"The project's quota for this operation has been exceeded.\",\r\n        [\"redirect-cancelled-by-user\" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',\r\n        [\"redirect-operation-pending\" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',\r\n        [\"rejected-credential\" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',\r\n        [\"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',\r\n        [\"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',\r\n        [\"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */]: \"The provided tenant ID does not match the Auth instance's tenant ID\",\r\n        [\"timeout\" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',\r\n        [\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */]: \"The user's credential is no longer valid. The user must sign in again.\",\r\n        [\"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +\r\n            'Try again later.',\r\n        [\"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted.  Please whitelist ' +\r\n            'the domain in the Firebase console.',\r\n        [\"unsupported-first-factor\" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */]: 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\r\n        [\"unsupported-persistence-type\" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',\r\n        [\"unsupported-tenant-operation\" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',\r\n        [\"unverified-email\" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',\r\n        [\"user-cancelled\" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',\r\n        [\"user-not-found\" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +\r\n            'have been deleted.',\r\n        [\"user-disabled\" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',\r\n        [\"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',\r\n        [\"user-signed-out\" /* AuthErrorCode.USER_SIGNED_OUT */]: '',\r\n        [\"weak-password\" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',\r\n        [\"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',\r\n        [\"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +\r\n            'different options. To avoid this error, call initializeAuth() with the ' +\r\n            'same options as when it was originally called, or call getAuth() to return the' +\r\n            ' already initialized instance.',\r\n        [\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is missing when sending request to the backend.',\r\n        [\"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is invalid when sending request to the backend.',\r\n        [\"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */]: 'The reCAPTCHA action is invalid when sending request to the backend.',\r\n        [\"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */]: 'reCAPTCHA Enterprise integration is not enabled for this project.',\r\n        [\"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */]: 'The reCAPTCHA client type is missing when sending request to the backend.',\r\n        [\"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is missing when sending request to the backend.',\r\n        [\"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */]: 'Invalid request parameters.',\r\n        [\"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is invalid when sending request to the backend.'\r\n    };\r\n}\r\nfunction _prodErrorMap() {\r\n    // We will include this one message in the prod error map since by the very\r\n    // nature of this error, developers will never be able to see the message\r\n    // using the debugErrorMap (which is installed during auth initialization).\r\n    return {\r\n        [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n            'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n            'starting any other Firebase SDK.'\r\n    };\r\n}\r\n/**\r\n * A verbose error map with detailed descriptions for most error codes.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst debugErrorMap = _debugErrorMap;\r\n/**\r\n * A minimal error map with all verbose error messages stripped.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst prodErrorMap = _prodErrorMap;\r\nconst _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());\r\n/**\r\n * A map of potential `Auth` error codes, for easier comparison with errors\r\n * thrown by the SDK.\r\n *\r\n * @remarks\r\n * Note that you can't tree-shake individual keys\r\n * in the map, so by using the map you might substantially increase your\r\n * bundle size.\r\n *\r\n * @public\r\n */\r\nconst AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\r\n    ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\r\n    ARGUMENT_ERROR: 'auth/argument-error',\r\n    APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\r\n    APP_NOT_INSTALLED: 'auth/app-not-installed',\r\n    CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\r\n    CODE_EXPIRED: 'auth/code-expired',\r\n    CORDOVA_NOT_READY: 'auth/cordova-not-ready',\r\n    CORS_UNSUPPORTED: 'auth/cors-unsupported',\r\n    CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\r\n    CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\r\n    CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\r\n    DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\r\n    DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\r\n    EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\r\n    EMAIL_EXISTS: 'auth/email-already-in-use',\r\n    EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\r\n    EXPIRED_OOB_CODE: 'auth/expired-action-code',\r\n    EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\r\n    INTERNAL_ERROR: 'auth/internal-error',\r\n    INVALID_API_KEY: 'auth/invalid-api-key',\r\n    INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\r\n    INVALID_APP_ID: 'auth/invalid-app-id',\r\n    INVALID_AUTH: 'auth/invalid-user-token',\r\n    INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\r\n    INVALID_CERT_HASH: 'auth/invalid-cert-hash',\r\n    INVALID_CODE: 'auth/invalid-verification-code',\r\n    INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\r\n    INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\r\n    INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\r\n    INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\r\n    INVALID_EMAIL: 'auth/invalid-email',\r\n    INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\r\n    INVALID_IDP_RESPONSE: 'auth/invalid-credential',\r\n    INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\r\n    INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\r\n    INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\r\n    INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\r\n    INVALID_OOB_CODE: 'auth/invalid-action-code',\r\n    INVALID_ORIGIN: 'auth/unauthorized-domain',\r\n    INVALID_PASSWORD: 'auth/wrong-password',\r\n    INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\r\n    INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\r\n    INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\r\n    INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\r\n    INVALID_SENDER: 'auth/invalid-sender',\r\n    INVALID_SESSION_INFO: 'auth/invalid-verification-id',\r\n    INVALID_TENANT_ID: 'auth/invalid-tenant-id',\r\n    MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\r\n    MFA_REQUIRED: 'auth/multi-factor-auth-required',\r\n    MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\r\n    MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\r\n    MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\r\n    MISSING_CODE: 'auth/missing-verification-code',\r\n    MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\r\n    MISSING_IFRAME_START: 'auth/missing-iframe-start',\r\n    MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\r\n    MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\r\n    MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\r\n    MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\r\n    MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\r\n    MISSING_SESSION_INFO: 'auth/missing-verification-id',\r\n    MODULE_DESTROYED: 'auth/app-deleted',\r\n    NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\r\n    NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\r\n    NULL_USER: 'auth/null-user',\r\n    NO_AUTH_EVENT: 'auth/no-auth-event',\r\n    NO_SUCH_PROVIDER: 'auth/no-such-provider',\r\n    OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\r\n    OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\r\n    POPUP_BLOCKED: 'auth/popup-blocked',\r\n    POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\r\n    PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\r\n    QUOTA_EXCEEDED: 'auth/quota-exceeded',\r\n    REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\r\n    REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\r\n    REJECTED_CREDENTIAL: 'auth/rejected-credential',\r\n    SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\r\n    SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\r\n    TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\r\n    TIMEOUT: 'auth/timeout',\r\n    TOKEN_EXPIRED: 'auth/user-token-expired',\r\n    TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\r\n    UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\r\n    UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\r\n    UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\r\n    UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\r\n    UNVERIFIED_EMAIL: 'auth/unverified-email',\r\n    USER_CANCELLED: 'auth/user-cancelled',\r\n    USER_DELETED: 'auth/user-not-found',\r\n    USER_DISABLED: 'auth/user-disabled',\r\n    USER_MISMATCH: 'auth/user-mismatch',\r\n    USER_SIGNED_OUT: 'auth/user-signed-out',\r\n    WEAK_PASSWORD: 'auth/weak-password',\r\n    WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\r\n    ALREADY_INITIALIZED: 'auth/already-initialized',\r\n    RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\r\n    MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\r\n    INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\r\n    INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\r\n    MISSING_CLIENT_TYPE: 'auth/missing-client-type',\r\n    MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\r\n    INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\r\n    INVALID_REQ_TYPE: 'auth/invalid-req-type'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logClient = new Logger('@firebase/auth');\r\nfunction _logWarn(msg, ...args) {\r\n    if (logClient.logLevel <= LogLevel.WARN) {\r\n        logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n    }\r\n}\r\nfunction _logError(msg, ...args) {\r\n    if (logClient.logLevel <= LogLevel.ERROR) {\r\n        logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _fail(authOrCode, ...rest) {\r\n    throw createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _createError(authOrCode, ...rest) {\r\n    return createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _errorWithCustomMessage(auth, code, message) {\r\n    const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });\r\n    const factory = new ErrorFactory('auth', 'Firebase', errorMap);\r\n    return factory.create(code, {\r\n        appName: auth.name\r\n    });\r\n}\r\nfunction _assertInstanceOf(auth, object, instance) {\r\n    const constructorInstance = instance;\r\n    if (!(object instanceof constructorInstance)) {\r\n        if (constructorInstance.name !== object.constructor.name) {\r\n            _fail(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        }\r\n        throw _errorWithCustomMessage(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +\r\n            `Did you pass a reference from a different Auth SDK?`);\r\n    }\r\n}\r\nfunction createErrorInternal(authOrCode, ...rest) {\r\n    if (typeof authOrCode !== 'string') {\r\n        const code = rest[0];\r\n        const fullParams = [...rest.slice(1)];\r\n        if (fullParams[0]) {\r\n            fullParams[0].appName = authOrCode.name;\r\n        }\r\n        return authOrCode._errorFactory.create(code, ...fullParams);\r\n    }\r\n    return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);\r\n}\r\nfunction _assert(assertion, authOrCode, ...rest) {\r\n    if (!assertion) {\r\n        throw createErrorInternal(authOrCode, ...rest);\r\n    }\r\n}\r\n/**\r\n * Unconditionally fails, throwing an internal error with the given message.\r\n *\r\n * @param failure type of failure encountered\r\n * @throws Error\r\n */\r\nfunction debugFail(failure) {\r\n    // Log the failure in addition to throw an exception, just in case the\r\n    // exception is swallowed.\r\n    const message = `INTERNAL ASSERTION FAILED: ` + failure;\r\n    _logError(message);\r\n    // NOTE: We don't use FirebaseError here because these are internal failures\r\n    // that cannot be handled by the user. (Also it would create a circular\r\n    // dependency between the error and assert modules which doesn't work.)\r\n    throw new Error(message);\r\n}\r\n/**\r\n * Fails if the given assertion condition is false, throwing an Error with the\r\n * given message if it did.\r\n *\r\n * @param assertion\r\n * @param message\r\n */\r\nfunction debugAssert(assertion, message) {\r\n    if (!assertion) {\r\n        debugFail(message);\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _getCurrentUrl() {\r\n    var _a;\r\n    return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';\r\n}\r\nfunction _isHttpOrHttps() {\r\n    return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\r\n}\r\nfunction _getCurrentScheme() {\r\n    var _a;\r\n    return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine whether the browser is working online\r\n */\r\nfunction _isOnline() {\r\n    if (typeof navigator !== 'undefined' &&\r\n        navigator &&\r\n        'onLine' in navigator &&\r\n        typeof navigator.onLine === 'boolean' &&\r\n        // Apply only for traditional web apps and Chrome extensions.\r\n        // This is especially true for Cordova apps which have unreliable\r\n        // navigator.onLine behavior unless cordova-plugin-network-information is\r\n        // installed which overwrites the native navigator.onLine value and\r\n        // defines navigator.connection.\r\n        (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {\r\n        return navigator.onLine;\r\n    }\r\n    // If we can't determine the state, assume it is online.\r\n    return true;\r\n}\r\nfunction _getUserLanguage() {\r\n    if (typeof navigator === 'undefined') {\r\n        return null;\r\n    }\r\n    const navigatorLanguage = navigator;\r\n    return (\r\n    // Most reliable, but only supported in Chrome/Firefox.\r\n    (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\r\n        // Supported in most browsers, but returns the language of the browser\r\n        // UI, not the language set in browser settings.\r\n        navigatorLanguage.language ||\r\n        // Couldn't determine language.\r\n        null);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A structure to help pick between a range of long and short delay durations\r\n * depending on the current environment. In general, the long delay is used for\r\n * mobile environments whereas short delays are used for desktop environments.\r\n */\r\nclass Delay {\r\n    constructor(shortDelay, longDelay) {\r\n        this.shortDelay = shortDelay;\r\n        this.longDelay = longDelay;\r\n        // Internal error when improperly initialized.\r\n        debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');\r\n        this.isMobile = isMobileCordova() || isReactNative();\r\n    }\r\n    get() {\r\n        if (!_isOnline()) {\r\n            // Pick the shorter timeout.\r\n            return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);\r\n        }\r\n        // If running in a mobile environment, return the long delay, otherwise\r\n        // return the short delay.\r\n        // This could be improved in the future to dynamically change based on other\r\n        // variables instead of just reading the current environment.\r\n        return this.isMobile ? this.longDelay : this.shortDelay;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _emulatorUrl(config, path) {\r\n    debugAssert(config.emulator, 'Emulator should always be set here');\r\n    const { url } = config.emulator;\r\n    if (!path) {\r\n        return url;\r\n    }\r\n    return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FetchProvider {\r\n    static initialize(fetchImpl, headersImpl, responseImpl) {\r\n        this.fetchImpl = fetchImpl;\r\n        if (headersImpl) {\r\n            this.headersImpl = headersImpl;\r\n        }\r\n        if (responseImpl) {\r\n            this.responseImpl = responseImpl;\r\n        }\r\n    }\r\n    static fetch() {\r\n        if (this.fetchImpl) {\r\n            return this.fetchImpl;\r\n        }\r\n        if (typeof self !== 'undefined' && 'fetch' in self) {\r\n            return self.fetch;\r\n        }\r\n        debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n    }\r\n    static headers() {\r\n        if (this.headersImpl) {\r\n            return this.headersImpl;\r\n        }\r\n        if (typeof self !== 'undefined' && 'Headers' in self) {\r\n            return self.Headers;\r\n        }\r\n        debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n    }\r\n    static response() {\r\n        if (this.responseImpl) {\r\n            return this.responseImpl;\r\n        }\r\n        if (typeof self !== 'undefined' && 'Response' in self) {\r\n            return self.Response;\r\n        }\r\n        debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Map from errors returned by the server to errors to developer visible errors\r\n */\r\nconst SERVER_ERROR_MAP = {\r\n    // Custom token errors.\r\n    [\"CREDENTIAL_MISMATCH\" /* ServerError.CREDENTIAL_MISMATCH */]: \"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */,\r\n    // This can only happen if the SDK sends a bad request.\r\n    [\"MISSING_CUSTOM_TOKEN\" /* ServerError.MISSING_CUSTOM_TOKEN */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n    // Create Auth URI errors.\r\n    [\"INVALID_IDENTIFIER\" /* ServerError.INVALID_IDENTIFIER */]: \"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */,\r\n    // This can only happen if the SDK sends a bad request.\r\n    [\"MISSING_CONTINUE_URI\" /* ServerError.MISSING_CONTINUE_URI */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n    // Sign in with email and password errors (some apply to sign up too).\r\n    [\"INVALID_PASSWORD\" /* ServerError.INVALID_PASSWORD */]: \"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */,\r\n    // This can only happen if the SDK sends a bad request.\r\n    [\"MISSING_PASSWORD\" /* ServerError.MISSING_PASSWORD */]: \"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */,\r\n    // Sign up with email and password errors.\r\n    [\"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */]: \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */,\r\n    [\"PASSWORD_LOGIN_DISABLED\" /* ServerError.PASSWORD_LOGIN_DISABLED */]: \"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,\r\n    // Verify assertion for sign in with credential errors:\r\n    [\"INVALID_IDP_RESPONSE\" /* ServerError.INVALID_IDP_RESPONSE */]: \"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */,\r\n    [\"INVALID_PENDING_TOKEN\" /* ServerError.INVALID_PENDING_TOKEN */]: \"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */,\r\n    [\"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,\r\n    // This can only happen if the SDK sends a bad request.\r\n    [\"MISSING_REQ_TYPE\" /* ServerError.MISSING_REQ_TYPE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n    // Send Password reset email errors:\r\n    [\"EMAIL_NOT_FOUND\" /* ServerError.EMAIL_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */,\r\n    [\"RESET_PASSWORD_EXCEED_LIMIT\" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n    [\"EXPIRED_OOB_CODE\" /* ServerError.EXPIRED_OOB_CODE */]: \"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */,\r\n    [\"INVALID_OOB_CODE\" /* ServerError.INVALID_OOB_CODE */]: \"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */,\r\n    // This can only happen if the SDK sends a bad request.\r\n    [\"MISSING_OOB_CODE\" /* ServerError.MISSING_OOB_CODE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n    // Operations that require ID token in request:\r\n    [\"CREDENTIAL_TOO_OLD_LOGIN_AGAIN\" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: \"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,\r\n    [\"INVALID_ID_TOKEN\" /* ServerError.INVALID_ID_TOKEN */]: \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */,\r\n    [\"TOKEN_EXPIRED\" /* ServerError.TOKEN_EXPIRED */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n    [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n    // Other errors.\r\n    [\"TOO_MANY_ATTEMPTS_TRY_LATER\" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n    // Phone Auth related errors.\r\n    [\"INVALID_CODE\" /* ServerError.INVALID_CODE */]: \"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */,\r\n    [\"INVALID_SESSION_INFO\" /* ServerError.INVALID_SESSION_INFO */]: \"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */,\r\n    [\"INVALID_TEMPORARY_PROOF\" /* ServerError.INVALID_TEMPORARY_PROOF */]: \"invalid-credential\" /* AuthErrorCode.INVALID_IDP_RESPONSE */,\r\n    [\"MISSING_SESSION_INFO\" /* ServerError.MISSING_SESSION_INFO */]: \"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */,\r\n    [\"SESSION_EXPIRED\" /* ServerError.SESSION_EXPIRED */]: \"code-expired\" /* AuthErrorCode.CODE_EXPIRED */,\r\n    // Other action code errors when additional settings passed.\r\n    // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\r\n    // This is OK as this error will be caught by client side validation.\r\n    [\"MISSING_ANDROID_PACKAGE_NAME\" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,\r\n    [\"UNAUTHORIZED_DOMAIN\" /* ServerError.UNAUTHORIZED_DOMAIN */]: \"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,\r\n    // getProjectConfig errors when clientId is passed.\r\n    [\"INVALID_OAUTH_CLIENT_ID\" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: \"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,\r\n    // User actions (sign-up or deletion) disabled errors.\r\n    [\"ADMIN_ONLY_OPERATION\" /* ServerError.ADMIN_ONLY_OPERATION */]: \"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,\r\n    // Multi factor related errors.\r\n    [\"INVALID_MFA_PENDING_CREDENTIAL\" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: \"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */,\r\n    [\"MFA_ENROLLMENT_NOT_FOUND\" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: \"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,\r\n    [\"MISSING_MFA_ENROLLMENT_ID\" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */,\r\n    [\"MISSING_MFA_PENDING_CREDENTIAL\" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: \"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */,\r\n    [\"SECOND_FACTOR_EXISTS\" /* ServerError.SECOND_FACTOR_EXISTS */]: \"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,\r\n    [\"SECOND_FACTOR_LIMIT_EXCEEDED\" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: \"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,\r\n    // Blocking functions related errors.\r\n    [\"BLOCKING_FUNCTION_ERROR_RESPONSE\" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n    // Recaptcha related errors.\r\n    [\"RECAPTCHA_NOT_ENABLED\" /* ServerError.RECAPTCHA_NOT_ENABLED */]: \"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,\r\n    [\"MISSING_RECAPTCHA_TOKEN\" /* ServerError.MISSING_RECAPTCHA_TOKEN */]: \"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,\r\n    [\"INVALID_RECAPTCHA_TOKEN\" /* ServerError.INVALID_RECAPTCHA_TOKEN */]: \"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,\r\n    [\"INVALID_RECAPTCHA_ACTION\" /* ServerError.INVALID_RECAPTCHA_ACTION */]: \"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,\r\n    [\"MISSING_CLIENT_TYPE\" /* ServerError.MISSING_CLIENT_TYPE */]: \"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */,\r\n    [\"MISSING_RECAPTCHA_VERSION\" /* ServerError.MISSING_RECAPTCHA_VERSION */]: \"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,\r\n    [\"INVALID_RECAPTCHA_VERSION\" /* ServerError.INVALID_RECAPTCHA_VERSION */]: \"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,\r\n    [\"INVALID_REQ_TYPE\" /* ServerError.INVALID_REQ_TYPE */]: \"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);\r\nfunction _addTidIfNecessary(auth, request) {\r\n    if (auth.tenantId && !request.tenantId) {\r\n        return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });\r\n    }\r\n    return request;\r\n}\r\nasync function _performApiRequest(auth, method, path, request, customErrorMap = {}) {\r\n    return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\r\n        let body = {};\r\n        let params = {};\r\n        if (request) {\r\n            if (method === \"GET\" /* HttpMethod.GET */) {\r\n                params = request;\r\n            }\r\n            else {\r\n                body = {\r\n                    body: JSON.stringify(request)\r\n                };\r\n            }\r\n        }\r\n        const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);\r\n        const headers = await auth._getAdditionalHeaders();\r\n        headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/json';\r\n        if (auth.languageCode) {\r\n            headers[\"X-Firebase-Locale\" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;\r\n        }\r\n        return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,\r\n            headers, referrerPolicy: 'no-referrer' }, body));\r\n    });\r\n}\r\nasync function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {\r\n    auth._canInitEmulator = false;\r\n    const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);\r\n    try {\r\n        const networkTimeout = new NetworkTimeout(auth);\r\n        const response = await Promise.race([\r\n            fetchFn(),\r\n            networkTimeout.promise\r\n        ]);\r\n        // If we've reached this point, the fetch succeeded and the networkTimeout\r\n        // didn't throw; clear the network timeout delay so that Node won't hang\r\n        networkTimeout.clearNetworkTimeout();\r\n        const json = await response.json();\r\n        if ('needConfirmation' in json) {\r\n            throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, json);\r\n        }\r\n        if (response.ok && !('errorMessage' in json)) {\r\n            return json;\r\n        }\r\n        else {\r\n            const errorMessage = response.ok ? json.errorMessage : json.error.message;\r\n            const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\r\n            if (serverErrorCode === \"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {\r\n                throw _makeTaggedError(auth, \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);\r\n            }\r\n            else if (serverErrorCode === \"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */) {\r\n                throw _makeTaggedError(auth, \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */, json);\r\n            }\r\n            else if (serverErrorCode === \"USER_DISABLED\" /* ServerError.USER_DISABLED */) {\r\n                throw _makeTaggedError(auth, \"user-disabled\" /* AuthErrorCode.USER_DISABLED */, json);\r\n            }\r\n            const authError = errorMap[serverErrorCode] ||\r\n                serverErrorCode\r\n                    .toLowerCase()\r\n                    .replace(/[_\\s]+/g, '-');\r\n            if (serverErrorMessage) {\r\n                throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\r\n            }\r\n            else {\r\n                _fail(auth, authError);\r\n            }\r\n        }\r\n    }\r\n    catch (e) {\r\n        if (e instanceof FirebaseError) {\r\n            throw e;\r\n        }\r\n        // Changing this to a different error code will log user out when there is a network error\r\n        // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\r\n        // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\r\n        _fail(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e) });\r\n    }\r\n}\r\nasync function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {\r\n    const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));\r\n    if ('mfaPendingCredential' in serverResponse) {\r\n        _fail(auth, \"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */, {\r\n            _serverResponse: serverResponse\r\n        });\r\n    }\r\n    return serverResponse;\r\n}\r\nfunction _getFinalTarget(auth, host, path, query) {\r\n    const base = `${host}${path}?${query}`;\r\n    if (!auth.config.emulator) {\r\n        return `${auth.config.apiScheme}://${base}`;\r\n    }\r\n    return _emulatorUrl(auth.config, base);\r\n}\r\nclass NetworkTimeout {\r\n    constructor(auth) {\r\n        this.auth = auth;\r\n        // Node timers and browser timers are fundamentally incompatible, but we\r\n        // don't care about the value here\r\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n        this.timer = null;\r\n        this.promise = new Promise((_, reject) => {\r\n            this.timer = setTimeout(() => {\r\n                return reject(_createError(this.auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n            }, DEFAULT_API_TIMEOUT_MS.get());\r\n        });\r\n    }\r\n    clearNetworkTimeout() {\r\n        clearTimeout(this.timer);\r\n    }\r\n}\r\nfunction _makeTaggedError(auth, code, response) {\r\n    const errorParams = {\r\n        appName: auth.name\r\n    };\r\n    if (response.email) {\r\n        errorParams.email = response.email;\r\n    }\r\n    if (response.phoneNumber) {\r\n        errorParams.phoneNumber = response.phoneNumber;\r\n    }\r\n    const error = _createError(auth, code, errorParams);\r\n    // We know customData is defined on error because errorParams is defined\r\n    error.customData._tokenResponse = response;\r\n    return error;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteAccount(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:delete\" /* Endpoint.DELETE_ACCOUNT */, request);\r\n}\r\nasync function deleteLinkedAccounts(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function getAccountInfo(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:lookup\" /* Endpoint.GET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction utcTimestampToDateString(utcTimestamp) {\r\n    if (!utcTimestamp) {\r\n        return undefined;\r\n    }\r\n    try {\r\n        // Convert to date object.\r\n        const date = new Date(Number(utcTimestamp));\r\n        // Test date is valid.\r\n        if (!isNaN(date.getTime())) {\r\n            // Convert to UTC date string.\r\n            return date.toUTCString();\r\n        }\r\n    }\r\n    catch (e) {\r\n        // Do nothing. undefined will be returned.\r\n    }\r\n    return undefined;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nfunction getIdToken(user, forceRefresh = false) {\r\n    return getModularInstance(user).getIdToken(forceRefresh);\r\n}\r\n/**\r\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getIdTokenResult(user, forceRefresh = false) {\r\n    const userInternal = getModularInstance(user);\r\n    const token = await userInternal.getIdToken(forceRefresh);\r\n    const claims = _parseToken(token);\r\n    _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;\r\n    const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];\r\n    return {\r\n        claims,\r\n        token,\r\n        authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),\r\n        issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),\r\n        expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),\r\n        signInProvider: signInProvider || null,\r\n        signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null\r\n    };\r\n}\r\nfunction secondsStringToMilliseconds(seconds) {\r\n    return Number(seconds) * 1000;\r\n}\r\nfunction _parseToken(token) {\r\n    const [algorithm, payload, signature] = token.split('.');\r\n    if (algorithm === undefined ||\r\n        payload === undefined ||\r\n        signature === undefined) {\r\n        _logError('JWT malformed, contained fewer than 3 sections');\r\n        return null;\r\n    }\r\n    try {\r\n        const decoded = base64Decode(payload);\r\n        if (!decoded) {\r\n            _logError('Failed to decode base64 JWT payload');\r\n            return null;\r\n        }\r\n        return JSON.parse(decoded);\r\n    }\r\n    catch (e) {\r\n        _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());\r\n        return null;\r\n    }\r\n}\r\n/**\r\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\r\n */\r\nfunction _tokenExpiresIn(token) {\r\n    const parsedToken = _parseToken(token);\r\n    _assert(parsedToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    return Number(parsedToken.exp) - Number(parsedToken.iat);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _logoutIfInvalidated(user, promise, bypassAuthState = false) {\r\n    if (bypassAuthState) {\r\n        return promise;\r\n    }\r\n    try {\r\n        return await promise;\r\n    }\r\n    catch (e) {\r\n        if (e instanceof FirebaseError && isUserInvalidated(e)) {\r\n            if (user.auth.currentUser === user) {\r\n                await user.auth.signOut();\r\n            }\r\n        }\r\n        throw e;\r\n    }\r\n}\r\nfunction isUserInvalidated({ code }) {\r\n    return (code === `auth/${\"user-disabled\" /* AuthErrorCode.USER_DISABLED */}` ||\r\n        code === `auth/${\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */}`);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ProactiveRefresh {\r\n    constructor(user) {\r\n        this.user = user;\r\n        this.isRunning = false;\r\n        // Node timers and browser timers return fundamentally different types.\r\n        // We don't actually care what the value is but TS won't accept unknown and\r\n        // we can't cast properly in both environments.\r\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n        this.timerId = null;\r\n        this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n    }\r\n    _start() {\r\n        if (this.isRunning) {\r\n            return;\r\n        }\r\n        this.isRunning = true;\r\n        this.schedule();\r\n    }\r\n    _stop() {\r\n        if (!this.isRunning) {\r\n            return;\r\n        }\r\n        this.isRunning = false;\r\n        if (this.timerId !== null) {\r\n            clearTimeout(this.timerId);\r\n        }\r\n    }\r\n    getInterval(wasError) {\r\n        var _a;\r\n        if (wasError) {\r\n            const interval = this.errorBackoff;\r\n            this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);\r\n            return interval;\r\n        }\r\n        else {\r\n            // Reset the error backoff\r\n            this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n            const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;\r\n            const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;\r\n            return Math.max(0, interval);\r\n        }\r\n    }\r\n    schedule(wasError = false) {\r\n        if (!this.isRunning) {\r\n            // Just in case...\r\n            return;\r\n        }\r\n        const interval = this.getInterval(wasError);\r\n        this.timerId = setTimeout(async () => {\r\n            await this.iteration();\r\n        }, interval);\r\n    }\r\n    async iteration() {\r\n        try {\r\n            await this.user.getIdToken(true);\r\n        }\r\n        catch (e) {\r\n            // Only retry on network errors\r\n            if ((e === null || e === void 0 ? void 0 : e.code) ===\r\n                `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n                this.schedule(/* wasError */ true);\r\n            }\r\n            return;\r\n        }\r\n        this.schedule();\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserMetadata {\r\n    constructor(createdAt, lastLoginAt) {\r\n        this.createdAt = createdAt;\r\n        this.lastLoginAt = lastLoginAt;\r\n        this._initializeTime();\r\n    }\r\n    _initializeTime() {\r\n        this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\r\n        this.creationTime = utcTimestampToDateString(this.createdAt);\r\n    }\r\n    _copy(metadata) {\r\n        this.createdAt = metadata.createdAt;\r\n        this.lastLoginAt = metadata.lastLoginAt;\r\n        this._initializeTime();\r\n    }\r\n    toJSON() {\r\n        return {\r\n            createdAt: this.createdAt,\r\n            lastLoginAt: this.lastLoginAt\r\n        };\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reloadWithoutSaving(user) {\r\n    var _a;\r\n    const auth = user.auth;\r\n    const idToken = await user.getIdToken();\r\n    const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));\r\n    _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    const coreAccount = response.users[0];\r\n    user._notifyReloadListener(coreAccount);\r\n    const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)\r\n        ? extractProviderData(coreAccount.providerUserInfo)\r\n        : [];\r\n    const providerData = mergeProviderData(user.providerData, newProviderData);\r\n    // Preserves the non-nonymous status of the stored user, even if no more\r\n    // credentials (federated or email/password) are linked to the user. If\r\n    // the user was previously anonymous, then use provider data to update.\r\n    // On the other hand, if it was not anonymous before, it should never be\r\n    // considered anonymous now.\r\n    const oldIsAnonymous = user.isAnonymous;\r\n    const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n    const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\r\n    const updates = {\r\n        uid: coreAccount.localId,\r\n        displayName: coreAccount.displayName || null,\r\n        photoURL: coreAccount.photoUrl || null,\r\n        email: coreAccount.email || null,\r\n        emailVerified: coreAccount.emailVerified || false,\r\n        phoneNumber: coreAccount.phoneNumber || null,\r\n        tenantId: coreAccount.tenantId || null,\r\n        providerData,\r\n        metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n        isAnonymous\r\n    };\r\n    Object.assign(user, updates);\r\n}\r\n/**\r\n * Reloads user account data, if signed in.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function reload(user) {\r\n    const userInternal = getModularInstance(user);\r\n    await _reloadWithoutSaving(userInternal);\r\n    // Even though the current user hasn't changed, update\r\n    // current user will trigger a persistence update w/ the\r\n    // new info.\r\n    await userInternal.auth._persistUserIfCurrent(userInternal);\r\n    userInternal.auth._notifyListenersIfCurrent(userInternal);\r\n}\r\nfunction mergeProviderData(original, newData) {\r\n    const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));\r\n    return [...deduped, ...newData];\r\n}\r\nfunction extractProviderData(providers) {\r\n    return providers.map((_a) => {\r\n        var { providerId } = _a, provider = __rest(_a, [\"providerId\"]);\r\n        return {\r\n            providerId,\r\n            uid: provider.rawId || '',\r\n            displayName: provider.displayName || null,\r\n            email: provider.email || null,\r\n            phoneNumber: provider.phoneNumber || null,\r\n            photoURL: provider.photoUrl || null\r\n        };\r\n    });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestStsToken(auth, refreshToken) {\r\n    const response = await _performFetchWithErrorHandling(auth, {}, async () => {\r\n        const body = querystring({\r\n            'grant_type': 'refresh_token',\r\n            'refresh_token': refreshToken\r\n        }).slice(1);\r\n        const { tokenApiHost, apiKey } = auth.config;\r\n        const url = _getFinalTarget(auth, tokenApiHost, \"/v1/token\" /* Endpoint.TOKEN */, `key=${apiKey}`);\r\n        const headers = await auth._getAdditionalHeaders();\r\n        headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';\r\n        return FetchProvider.fetch()(url, {\r\n            method: \"POST\" /* HttpMethod.POST */,\r\n            headers,\r\n            body\r\n        });\r\n    });\r\n    // The response comes back in snake_case. Convert to camel:\r\n    return {\r\n        accessToken: response.access_token,\r\n        expiresIn: response.expires_in,\r\n        refreshToken: response.refresh_token\r\n    };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\r\n * it references AuthInternal which has a circular dependency with UserInternal.\r\n *\r\n * @internal\r\n */\r\nclass StsTokenManager {\r\n    constructor() {\r\n        this.refreshToken = null;\r\n        this.accessToken = null;\r\n        this.expirationTime = null;\r\n    }\r\n    get isExpired() {\r\n        return (!this.expirationTime ||\r\n            Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);\r\n    }\r\n    updateFromServerResponse(response) {\r\n        _assert(response.idToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        _assert(typeof response.idToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        _assert(typeof response.refreshToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\r\n            ? Number(response.expiresIn)\r\n            : _tokenExpiresIn(response.idToken);\r\n        this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);\r\n    }\r\n    async getToken(auth, forceRefresh = false) {\r\n        _assert(!this.accessToken || this.refreshToken, auth, \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */);\r\n        if (!forceRefresh && this.accessToken && !this.isExpired) {\r\n            return this.accessToken;\r\n        }\r\n        if (this.refreshToken) {\r\n            await this.refresh(auth, this.refreshToken);\r\n            return this.accessToken;\r\n        }\r\n        return null;\r\n    }\r\n    clearRefreshToken() {\r\n        this.refreshToken = null;\r\n    }\r\n    async refresh(auth, oldToken) {\r\n        const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);\r\n        this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));\r\n    }\r\n    updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {\r\n        this.refreshToken = refreshToken || null;\r\n        this.accessToken = accessToken || null;\r\n        this.expirationTime = Date.now() + expiresInSec * 1000;\r\n    }\r\n    static fromJSON(appName, object) {\r\n        const { refreshToken, accessToken, expirationTime } = object;\r\n        const manager = new StsTokenManager();\r\n        if (refreshToken) {\r\n            _assert(typeof refreshToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n                appName\r\n            });\r\n            manager.refreshToken = refreshToken;\r\n        }\r\n        if (accessToken) {\r\n            _assert(typeof accessToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n                appName\r\n            });\r\n            manager.accessToken = accessToken;\r\n        }\r\n        if (expirationTime) {\r\n            _assert(typeof expirationTime === 'number', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n                appName\r\n            });\r\n            manager.expirationTime = expirationTime;\r\n        }\r\n        return manager;\r\n    }\r\n    toJSON() {\r\n        return {\r\n            refreshToken: this.refreshToken,\r\n            accessToken: this.accessToken,\r\n            expirationTime: this.expirationTime\r\n        };\r\n    }\r\n    _assign(stsTokenManager) {\r\n        this.accessToken = stsTokenManager.accessToken;\r\n        this.refreshToken = stsTokenManager.refreshToken;\r\n        this.expirationTime = stsTokenManager.expirationTime;\r\n    }\r\n    _clone() {\r\n        return Object.assign(new StsTokenManager(), this.toJSON());\r\n    }\r\n    _performRefresh() {\r\n        return debugFail('not implemented');\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction assertStringOrUndefined(assertion, appName) {\r\n    _assert(typeof assertion === 'string' || typeof assertion === 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, { appName });\r\n}\r\nclass UserImpl {\r\n    constructor(_a) {\r\n        var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, [\"uid\", \"auth\", \"stsTokenManager\"]);\r\n        // For the user object, provider is always Firebase.\r\n        this.providerId = \"firebase\" /* ProviderId.FIREBASE */;\r\n        this.proactiveRefresh = new ProactiveRefresh(this);\r\n        this.reloadUserInfo = null;\r\n        this.reloadListener = null;\r\n        this.uid = uid;\r\n        this.auth = auth;\r\n        this.stsTokenManager = stsTokenManager;\r\n        this.accessToken = stsTokenManager.accessToken;\r\n        this.displayName = opt.displayName || null;\r\n        this.email = opt.email || null;\r\n        this.emailVerified = opt.emailVerified || false;\r\n        this.phoneNumber = opt.phoneNumber || null;\r\n        this.photoURL = opt.photoURL || null;\r\n        this.isAnonymous = opt.isAnonymous || false;\r\n        this.tenantId = opt.tenantId || null;\r\n        this.providerData = opt.providerData ? [...opt.providerData] : [];\r\n        this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);\r\n    }\r\n    async getIdToken(forceRefresh) {\r\n        const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));\r\n        _assert(accessToken, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        if (this.accessToken !== accessToken) {\r\n            this.accessToken = accessToken;\r\n            await this.auth._persistUserIfCurrent(this);\r\n            this.auth._notifyListenersIfCurrent(this);\r\n        }\r\n        return accessToken;\r\n    }\r\n    getIdTokenResult(forceRefresh) {\r\n        return getIdTokenResult(this, forceRefresh);\r\n    }\r\n    reload() {\r\n        return reload(this);\r\n    }\r\n    _assign(user) {\r\n        if (this === user) {\r\n            return;\r\n        }\r\n        _assert(this.uid === user.uid, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        this.displayName = user.displayName;\r\n        this.photoURL = user.photoURL;\r\n        this.email = user.email;\r\n        this.emailVerified = user.emailVerified;\r\n        this.phoneNumber = user.phoneNumber;\r\n        this.isAnonymous = user.isAnonymous;\r\n        this.tenantId = user.tenantId;\r\n        this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n        this.metadata._copy(user.metadata);\r\n        this.stsTokenManager._assign(user.stsTokenManager);\r\n    }\r\n    _clone(auth) {\r\n        const newUser = new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));\r\n        newUser.metadata._copy(this.metadata);\r\n        return newUser;\r\n    }\r\n    _onReload(callback) {\r\n        // There should only ever be one listener, and that is a single instance of MultiFactorUser\r\n        _assert(!this.reloadListener, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        this.reloadListener = callback;\r\n        if (this.reloadUserInfo) {\r\n            this._notifyReloadListener(this.reloadUserInfo);\r\n            this.reloadUserInfo = null;\r\n        }\r\n    }\r\n    _notifyReloadListener(userInfo) {\r\n        if (this.reloadListener) {\r\n            this.reloadListener(userInfo);\r\n        }\r\n        else {\r\n            // If no listener is subscribed yet, save the result so it's available when they do subscribe\r\n            this.reloadUserInfo = userInfo;\r\n        }\r\n    }\r\n    _startProactiveRefresh() {\r\n        this.proactiveRefresh._start();\r\n    }\r\n    _stopProactiveRefresh() {\r\n        this.proactiveRefresh._stop();\r\n    }\r\n    async _updateTokensIfNecessary(response, reload = false) {\r\n        let tokensRefreshed = false;\r\n        if (response.idToken &&\r\n            response.idToken !== this.stsTokenManager.accessToken) {\r\n            this.stsTokenManager.updateFromServerResponse(response);\r\n            tokensRefreshed = true;\r\n        }\r\n        if (reload) {\r\n            await _reloadWithoutSaving(this);\r\n        }\r\n        await this.auth._persistUserIfCurrent(this);\r\n        if (tokensRefreshed) {\r\n            this.auth._notifyListenersIfCurrent(this);\r\n        }\r\n    }\r\n    async delete() {\r\n        const idToken = await this.getIdToken();\r\n        await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\r\n        this.stsTokenManager.clearRefreshToken();\r\n        // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\r\n        //       cancels pending actions...\r\n        return this.auth.signOut();\r\n    }\r\n    toJSON() {\r\n        return Object.assign(Object.assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(userInfo => (Object.assign({}, userInfo))), stsTokenManager: this.stsTokenManager.toJSON(), \r\n            // Redirect event ID must be maintained in case there is a pending\r\n            // redirect event.\r\n            _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), { \r\n            // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\r\n            apiKey: this.auth.config.apiKey, appName: this.auth.name });\r\n    }\r\n    get refreshToken() {\r\n        return this.stsTokenManager.refreshToken || '';\r\n    }\r\n    static _fromJSON(auth, object) {\r\n        var _a, _b, _c, _d, _e, _f, _g, _h;\r\n        const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;\r\n        const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;\r\n        const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;\r\n        const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;\r\n        const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;\r\n        const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;\r\n        const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;\r\n        const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;\r\n        const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;\r\n        _assert(uid && plainObjectTokenManager, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);\r\n        _assert(typeof uid === 'string', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        assertStringOrUndefined(displayName, auth.name);\r\n        assertStringOrUndefined(email, auth.name);\r\n        _assert(typeof emailVerified === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        _assert(typeof isAnonymous === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        assertStringOrUndefined(phoneNumber, auth.name);\r\n        assertStringOrUndefined(photoURL, auth.name);\r\n        assertStringOrUndefined(tenantId, auth.name);\r\n        assertStringOrUndefined(_redirectEventId, auth.name);\r\n        assertStringOrUndefined(createdAt, auth.name);\r\n        assertStringOrUndefined(lastLoginAt, auth.name);\r\n        const user = new UserImpl({\r\n            uid,\r\n            auth,\r\n            email,\r\n            emailVerified,\r\n            displayName,\r\n            isAnonymous,\r\n            photoURL,\r\n            phoneNumber,\r\n            tenantId,\r\n            stsTokenManager,\r\n            createdAt,\r\n            lastLoginAt\r\n        });\r\n        if (providerData && Array.isArray(providerData)) {\r\n            user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n        }\r\n        if (_redirectEventId) {\r\n            user._redirectEventId = _redirectEventId;\r\n        }\r\n        return user;\r\n    }\r\n    /**\r\n     * Initialize a User from an idToken server response\r\n     * @param auth\r\n     * @param idTokenResponse\r\n     */\r\n    static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {\r\n        const stsTokenManager = new StsTokenManager();\r\n        stsTokenManager.updateFromServerResponse(idTokenResponse);\r\n        // Initialize the Firebase Auth user.\r\n        const user = new UserImpl({\r\n            uid: idTokenResponse.localId,\r\n            auth,\r\n            stsTokenManager,\r\n            isAnonymous\r\n        });\r\n        // Updates the user info and data and resolves with a user instance.\r\n        await _reloadWithoutSaving(user);\r\n        return user;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst instanceCache = new Map();\r\nfunction _getInstance(cls) {\r\n    debugAssert(cls instanceof Function, 'Expected a class definition');\r\n    let instance = instanceCache.get(cls);\r\n    if (instance) {\r\n        debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');\r\n        return instance;\r\n    }\r\n    instance = new cls();\r\n    instanceCache.set(cls, instance);\r\n    return instance;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass InMemoryPersistence {\r\n    constructor() {\r\n        this.type = \"NONE\" /* PersistenceType.NONE */;\r\n        this.storage = {};\r\n    }\r\n    async _isAvailable() {\r\n        return true;\r\n    }\r\n    async _set(key, value) {\r\n        this.storage[key] = value;\r\n    }\r\n    async _get(key) {\r\n        const value = this.storage[key];\r\n        return value === undefined ? null : value;\r\n    }\r\n    async _remove(key) {\r\n        delete this.storage[key];\r\n    }\r\n    _addListener(_key, _listener) {\r\n        // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n        return;\r\n    }\r\n    _removeListener(_key, _listener) {\r\n        // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n        return;\r\n    }\r\n}\r\nInMemoryPersistence.type = 'NONE';\r\n/**\r\n * An implementation of {@link Persistence} of type 'NONE'.\r\n *\r\n * @public\r\n */\r\nconst inMemoryPersistence = InMemoryPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _persistenceKeyName(key, apiKey, appName) {\r\n    return `${\"firebase\" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;\r\n}\r\nclass PersistenceUserManager {\r\n    constructor(persistence, auth, userKey) {\r\n        this.persistence = persistence;\r\n        this.auth = auth;\r\n        this.userKey = userKey;\r\n        const { config, name } = this.auth;\r\n        this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\r\n        this.fullPersistenceKey = _persistenceKeyName(\"persistence\" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);\r\n        this.boundEventHandler = auth._onStorageEvent.bind(auth);\r\n        this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\r\n    }\r\n    setCurrentUser(user) {\r\n        return this.persistence._set(this.fullUserKey, user.toJSON());\r\n    }\r\n    async getCurrentUser() {\r\n        const blob = await this.persistence._get(this.fullUserKey);\r\n        return blob ? UserImpl._fromJSON(this.auth, blob) : null;\r\n    }\r\n    removeCurrentUser() {\r\n        return this.persistence._remove(this.fullUserKey);\r\n    }\r\n    savePersistenceForRedirect() {\r\n        return this.persistence._set(this.fullPersistenceKey, this.persistence.type);\r\n    }\r\n    async setPersistence(newPersistence) {\r\n        if (this.persistence === newPersistence) {\r\n            return;\r\n        }\r\n        const currentUser = await this.getCurrentUser();\r\n        await this.removeCurrentUser();\r\n        this.persistence = newPersistence;\r\n        if (currentUser) {\r\n            return this.setCurrentUser(currentUser);\r\n        }\r\n    }\r\n    delete() {\r\n        this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\r\n    }\r\n    static async create(auth, persistenceHierarchy, userKey = \"authUser\" /* KeyName.AUTH_USER */) {\r\n        if (!persistenceHierarchy.length) {\r\n            return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);\r\n        }\r\n        // Eliminate any persistences that are not available\r\n        const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n            if (await persistence._isAvailable()) {\r\n                return persistence;\r\n            }\r\n            return undefined;\r\n        }))).filter(persistence => persistence);\r\n        // Fall back to the first persistence listed, or in memory if none available\r\n        let selectedPersistence = availablePersistences[0] ||\r\n            _getInstance(inMemoryPersistence);\r\n        const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\r\n        // Pull out the existing user, setting the chosen persistence to that\r\n        // persistence if the user exists.\r\n        let userToMigrate = null;\r\n        // Note, here we check for a user in _all_ persistences, not just the\r\n        // ones deemed available. If we can migrate a user out of a broken\r\n        // persistence, we will (but only if that persistence supports migration).\r\n        for (const persistence of persistenceHierarchy) {\r\n            try {\r\n                const blob = await persistence._get(key);\r\n                if (blob) {\r\n                    const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\r\n                    if (persistence !== selectedPersistence) {\r\n                        userToMigrate = user;\r\n                    }\r\n                    selectedPersistence = persistence;\r\n                    break;\r\n                }\r\n            }\r\n            catch (_a) { }\r\n        }\r\n        // If we find the user in a persistence that does support migration, use\r\n        // that migration path (of only persistences that support migration)\r\n        const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);\r\n        // If the persistence does _not_ allow migration, just finish off here\r\n        if (!selectedPersistence._shouldAllowMigration ||\r\n            !migrationHierarchy.length) {\r\n            return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n        }\r\n        selectedPersistence = migrationHierarchy[0];\r\n        if (userToMigrate) {\r\n            // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\r\n            // we'll just let it bubble to surface the error.\r\n            await selectedPersistence._set(key, userToMigrate.toJSON());\r\n        }\r\n        // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\r\n        // such as users getting stuck with a previous account after signing out and refreshing the tab.\r\n        await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n            if (persistence !== selectedPersistence) {\r\n                try {\r\n                    await persistence._remove(key);\r\n                }\r\n                catch (_a) { }\r\n            }\r\n        }));\r\n        return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine the browser for the purposes of reporting usage to the API\r\n */\r\nfunction _getBrowserName(userAgent) {\r\n    const ua = userAgent.toLowerCase();\r\n    if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\r\n        return \"Opera\" /* BrowserName.OPERA */;\r\n    }\r\n    else if (_isIEMobile(ua)) {\r\n        // Windows phone IEMobile browser.\r\n        return \"IEMobile\" /* BrowserName.IEMOBILE */;\r\n    }\r\n    else if (ua.includes('msie') || ua.includes('trident/')) {\r\n        return \"IE\" /* BrowserName.IE */;\r\n    }\r\n    else if (ua.includes('edge/')) {\r\n        return \"Edge\" /* BrowserName.EDGE */;\r\n    }\r\n    else if (_isFirefox(ua)) {\r\n        return \"Firefox\" /* BrowserName.FIREFOX */;\r\n    }\r\n    else if (ua.includes('silk/')) {\r\n        return \"Silk\" /* BrowserName.SILK */;\r\n    }\r\n    else if (_isBlackBerry(ua)) {\r\n        // Blackberry browser.\r\n        return \"Blackberry\" /* BrowserName.BLACKBERRY */;\r\n    }\r\n    else if (_isWebOS(ua)) {\r\n        // WebOS default browser.\r\n        return \"Webos\" /* BrowserName.WEBOS */;\r\n    }\r\n    else if (_isSafari(ua)) {\r\n        return \"Safari\" /* BrowserName.SAFARI */;\r\n    }\r\n    else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&\r\n        !ua.includes('edge/')) {\r\n        return \"Chrome\" /* BrowserName.CHROME */;\r\n    }\r\n    else if (_isAndroid(ua)) {\r\n        // Android stock browser.\r\n        return \"Android\" /* BrowserName.ANDROID */;\r\n    }\r\n    else {\r\n        // Most modern browsers have name/version at end of user agent string.\r\n        const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\r\n        const matches = userAgent.match(re);\r\n        if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {\r\n            return matches[1];\r\n        }\r\n    }\r\n    return \"Other\" /* BrowserName.OTHER */;\r\n}\r\nfunction _isFirefox(ua = getUA()) {\r\n    return /firefox\\//i.test(ua);\r\n}\r\nfunction _isSafari(userAgent = getUA()) {\r\n    const ua = userAgent.toLowerCase();\r\n    return (ua.includes('safari/') &&\r\n        !ua.includes('chrome/') &&\r\n        !ua.includes('crios/') &&\r\n        !ua.includes('android'));\r\n}\r\nfunction _isChromeIOS(ua = getUA()) {\r\n    return /crios\\//i.test(ua);\r\n}\r\nfunction _isIEMobile(ua = getUA()) {\r\n    return /iemobile/i.test(ua);\r\n}\r\nfunction _isAndroid(ua = getUA()) {\r\n    return /android/i.test(ua);\r\n}\r\nfunction _isBlackBerry(ua = getUA()) {\r\n    return /blackberry/i.test(ua);\r\n}\r\nfunction _isWebOS(ua = getUA()) {\r\n    return /webos/i.test(ua);\r\n}\r\nfunction _isIOS(ua = getUA()) {\r\n    return (/iphone|ipad|ipod/i.test(ua) ||\r\n        (/macintosh/i.test(ua) && /mobile/i.test(ua)));\r\n}\r\nfunction _isIOS7Or8(ua = getUA()) {\r\n    return (/(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\r\n        /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua));\r\n}\r\nfunction _isIOSStandalone(ua = getUA()) {\r\n    var _a;\r\n    return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);\r\n}\r\nfunction _isIE10() {\r\n    return isIE() && document.documentMode === 10;\r\n}\r\nfunction _isMobileBrowser(ua = getUA()) {\r\n    // TODO: implement getBrowserName equivalent for OS.\r\n    return (_isIOS(ua) ||\r\n        _isAndroid(ua) ||\r\n        _isWebOS(ua) ||\r\n        _isBlackBerry(ua) ||\r\n        /windows phone/i.test(ua) ||\r\n        _isIEMobile(ua));\r\n}\r\nfunction _isIframe() {\r\n    try {\r\n        // Check that the current window is not the top window.\r\n        // If so, return true.\r\n        return !!(window && window !== window.top);\r\n    }\r\n    catch (e) {\r\n        return false;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/*\r\n * Determine the SDK version string\r\n */\r\nfunction _getClientVersion(clientPlatform, frameworks = []) {\r\n    let reportedPlatform;\r\n    switch (clientPlatform) {\r\n        case \"Browser\" /* ClientPlatform.BROWSER */:\r\n            // In a browser environment, report the browser name.\r\n            reportedPlatform = _getBrowserName(getUA());\r\n            break;\r\n        case \"Worker\" /* ClientPlatform.WORKER */:\r\n            // Technically a worker runs from a browser but we need to differentiate a\r\n            // worker from a browser.\r\n            // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\r\n            reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\r\n            break;\r\n        default:\r\n            reportedPlatform = clientPlatform;\r\n    }\r\n    const reportedFrameworks = frameworks.length\r\n        ? frameworks.join(',')\r\n        : 'FirebaseCore-web'; /* default value if no other framework is used */\r\n    return `${reportedPlatform}/${\"JsCore\" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getRecaptchaParams(auth) {\r\n    return ((await _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/recaptchaParams\" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');\r\n}\r\nasync function getRecaptchaConfig(auth, request) {\r\n    return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/recaptchaConfig\" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isV2(grecaptcha) {\r\n    return (grecaptcha !== undefined &&\r\n        grecaptcha.getResponse !== undefined);\r\n}\r\nfunction isEnterprise(grecaptcha) {\r\n    return (grecaptcha !== undefined &&\r\n        grecaptcha.enterprise !== undefined);\r\n}\r\nclass RecaptchaConfig {\r\n    constructor(response) {\r\n        /**\r\n         * The reCAPTCHA site key.\r\n         */\r\n        this.siteKey = '';\r\n        /**\r\n         * The reCAPTCHA enablement status of the {@link EmailAuthProvider} for the current tenant.\r\n         */\r\n        this.emailPasswordEnabled = false;\r\n        if (response.recaptchaKey === undefined) {\r\n            throw new Error('recaptchaKey undefined');\r\n        }\r\n        // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\r\n        this.siteKey = response.recaptchaKey.split('/')[3];\r\n        this.emailPasswordEnabled = response.recaptchaEnforcementState.some(enforcementState => enforcementState.provider === 'EMAIL_PASSWORD_PROVIDER' &&\r\n            enforcementState.enforcementState !== 'OFF');\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getScriptParentElement() {\r\n    var _a, _b;\r\n    return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;\r\n}\r\nfunction _loadJS(url) {\r\n    // TODO: consider adding timeout support & cancellation\r\n    return new Promise((resolve, reject) => {\r\n        const el = document.createElement('script');\r\n        el.setAttribute('src', url);\r\n        el.onload = resolve;\r\n        el.onerror = e => {\r\n            const error = _createError(\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n            error.customData = e;\r\n            reject(error);\r\n        };\r\n        el.type = 'text/javascript';\r\n        el.charset = 'UTF-8';\r\n        getScriptParentElement().appendChild(el);\r\n    });\r\n}\r\nfunction _generateCallbackName(prefix) {\r\n    return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\r\n}\n\n/* eslint-disable @typescript-eslint/no-require-imports */\r\nconst RECAPTCHA_ENTERPRISE_URL = 'https://www.google.com/recaptcha/enterprise.js?render=';\r\nconst RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\r\nconst FAKE_TOKEN = 'NO_RECAPTCHA';\r\nclass RecaptchaEnterpriseVerifier {\r\n    /**\r\n     *\r\n     * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n     *\r\n     */\r\n    constructor(authExtern) {\r\n        /**\r\n         * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\r\n         */\r\n        this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\r\n        this.auth = _castAuth(authExtern);\r\n    }\r\n    /**\r\n     * Executes the verification process.\r\n     *\r\n     * @returns A Promise for a token that can be used to assert the validity of a request.\r\n     */\r\n    async verify(action = 'verify', forceRefresh = false) {\r\n        async function retrieveSiteKey(auth) {\r\n            if (!forceRefresh) {\r\n                if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\r\n                    return auth._agentRecaptchaConfig.siteKey;\r\n                }\r\n                if (auth.tenantId != null &&\r\n                    auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {\r\n                    return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\r\n                }\r\n            }\r\n            return new Promise(async (resolve, reject) => {\r\n                getRecaptchaConfig(auth, {\r\n                    clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n                    version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n                })\r\n                    .then(response => {\r\n                    if (response.recaptchaKey === undefined) {\r\n                        reject(new Error('recaptcha Enterprise site key undefined'));\r\n                    }\r\n                    else {\r\n                        const config = new RecaptchaConfig(response);\r\n                        if (auth.tenantId == null) {\r\n                            auth._agentRecaptchaConfig = config;\r\n                        }\r\n                        else {\r\n                            auth._tenantRecaptchaConfigs[auth.tenantId] = config;\r\n                        }\r\n                        return resolve(config.siteKey);\r\n                    }\r\n                })\r\n                    .catch(error => {\r\n                    reject(error);\r\n                });\r\n            });\r\n        }\r\n        function retrieveRecaptchaToken(siteKey, resolve, reject) {\r\n            const grecaptcha = window.grecaptcha;\r\n            if (isEnterprise(grecaptcha)) {\r\n                grecaptcha.enterprise.ready(() => {\r\n                    grecaptcha.enterprise\r\n                        .execute(siteKey, { action })\r\n                        .then(token => {\r\n                        resolve(token);\r\n                    })\r\n                        .catch(() => {\r\n                        resolve(FAKE_TOKEN);\r\n                    });\r\n                });\r\n            }\r\n            else {\r\n                reject(Error('No reCAPTCHA enterprise script loaded.'));\r\n            }\r\n        }\r\n        return new Promise((resolve, reject) => {\r\n            retrieveSiteKey(this.auth)\r\n                .then(siteKey => {\r\n                if (!forceRefresh && isEnterprise(window.grecaptcha)) {\r\n                    retrieveRecaptchaToken(siteKey, resolve, reject);\r\n                }\r\n                else {\r\n                    if (typeof window === 'undefined') {\r\n                        reject(new Error('RecaptchaVerifier is only supported in browser'));\r\n                        return;\r\n                    }\r\n                    _loadJS(RECAPTCHA_ENTERPRISE_URL + siteKey)\r\n                        .then(() => {\r\n                        retrieveRecaptchaToken(siteKey, resolve, reject);\r\n                    })\r\n                        .catch(error => {\r\n                        reject(error);\r\n                    });\r\n                }\r\n            })\r\n                .catch(error => {\r\n                reject(error);\r\n            });\r\n        });\r\n    }\r\n}\r\nasync function injectRecaptchaFields(auth, request, action, captchaResp = false) {\r\n    const verifier = new RecaptchaEnterpriseVerifier(auth);\r\n    let captchaResponse;\r\n    try {\r\n        captchaResponse = await verifier.verify(action);\r\n    }\r\n    catch (error) {\r\n        captchaResponse = await verifier.verify(action, true);\r\n    }\r\n    const newRequest = Object.assign({}, request);\r\n    if (!captchaResp) {\r\n        Object.assign(newRequest, { captchaResponse });\r\n    }\r\n    else {\r\n        Object.assign(newRequest, { 'captchaResp': captchaResponse });\r\n    }\r\n    Object.assign(newRequest, { 'clientType': \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */ });\r\n    Object.assign(newRequest, {\r\n        'recaptchaVersion': \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n    });\r\n    return newRequest;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthMiddlewareQueue {\r\n    constructor(auth) {\r\n        this.auth = auth;\r\n        this.queue = [];\r\n    }\r\n    pushCallback(callback, onAbort) {\r\n        // The callback could be sync or async. Wrap it into a\r\n        // function that is always async.\r\n        const wrappedCallback = (user) => new Promise((resolve, reject) => {\r\n            try {\r\n                const result = callback(user);\r\n                // Either resolve with existing promise or wrap a non-promise\r\n                // return value into a promise.\r\n                resolve(result);\r\n            }\r\n            catch (e) {\r\n                // Sync callback throws.\r\n                reject(e);\r\n            }\r\n        });\r\n        // Attach the onAbort if present\r\n        wrappedCallback.onAbort = onAbort;\r\n        this.queue.push(wrappedCallback);\r\n        const index = this.queue.length - 1;\r\n        return () => {\r\n            // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\r\n            // indexing of other elements.\r\n            this.queue[index] = () => Promise.resolve();\r\n        };\r\n    }\r\n    async runMiddleware(nextUser) {\r\n        if (this.auth.currentUser === nextUser) {\r\n            return;\r\n        }\r\n        // While running the middleware, build a temporary stack of onAbort\r\n        // callbacks to call if one middleware callback rejects.\r\n        const onAbortStack = [];\r\n        try {\r\n            for (const beforeStateCallback of this.queue) {\r\n                await beforeStateCallback(nextUser);\r\n                // Only push the onAbort if the callback succeeds\r\n                if (beforeStateCallback.onAbort) {\r\n                    onAbortStack.push(beforeStateCallback.onAbort);\r\n                }\r\n            }\r\n        }\r\n        catch (e) {\r\n            // Run all onAbort, with separate try/catch to ignore any errors and\r\n            // continue\r\n            onAbortStack.reverse();\r\n            for (const onAbort of onAbortStack) {\r\n                try {\r\n                    onAbort();\r\n                }\r\n                catch (_) {\r\n                    /* swallow error */\r\n                }\r\n            }\r\n            throw this.auth._errorFactory.create(\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */, {\r\n                originalMessage: e === null || e === void 0 ? void 0 : e.message\r\n            });\r\n        }\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthImpl {\r\n    constructor(app, heartbeatServiceProvider, appCheckServiceProvider, config) {\r\n        this.app = app;\r\n        this.heartbeatServiceProvider = heartbeatServiceProvider;\r\n        this.appCheckServiceProvider = appCheckServiceProvider;\r\n        this.config = config;\r\n        this.currentUser = null;\r\n        this.emulatorConfig = null;\r\n        this.operations = Promise.resolve();\r\n        this.authStateSubscription = new Subscription(this);\r\n        this.idTokenSubscription = new Subscription(this);\r\n        this.beforeStateQueue = new AuthMiddlewareQueue(this);\r\n        this.redirectUser = null;\r\n        this.isProactiveRefreshEnabled = false;\r\n        // Any network calls will set this to true and prevent subsequent emulator\r\n        // initialization\r\n        this._canInitEmulator = true;\r\n        this._isInitialized = false;\r\n        this._deleted = false;\r\n        this._initializationPromise = null;\r\n        this._popupRedirectResolver = null;\r\n        this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;\r\n        this._agentRecaptchaConfig = null;\r\n        this._tenantRecaptchaConfigs = {};\r\n        // Tracks the last notified UID for state change listeners to prevent\r\n        // repeated calls to the callbacks. Undefined means it's never been\r\n        // called, whereas null means it's been called with a signed out user\r\n        this.lastNotifiedUid = undefined;\r\n        this.languageCode = null;\r\n        this.tenantId = null;\r\n        this.settings = { appVerificationDisabledForTesting: false };\r\n        this.frameworks = [];\r\n        this.name = app.name;\r\n        this.clientVersion = config.sdkClientVersion;\r\n    }\r\n    _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {\r\n        if (popupRedirectResolver) {\r\n            this._popupRedirectResolver = _getInstance(popupRedirectResolver);\r\n        }\r\n        // Have to check for app deletion throughout initialization (after each\r\n        // promise resolution)\r\n        this._initializationPromise = this.queue(async () => {\r\n            var _a, _b;\r\n            if (this._deleted) {\r\n                return;\r\n            }\r\n            this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);\r\n            if (this._deleted) {\r\n                return;\r\n            }\r\n            // Initialize the resolver early if necessary (only applicable to web:\r\n            // this will cause the iframe to load immediately in certain cases)\r\n            if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {\r\n                // If this fails, don't halt auth loading\r\n                try {\r\n                    await this._popupRedirectResolver._initialize(this);\r\n                }\r\n                catch (e) {\r\n                    /* Ignore the error */\r\n                }\r\n            }\r\n            await this.initializeCurrentUser(popupRedirectResolver);\r\n            this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;\r\n            if (this._deleted) {\r\n                return;\r\n            }\r\n            this._isInitialized = true;\r\n        });\r\n        return this._initializationPromise;\r\n    }\r\n    /**\r\n     * If the persistence is changed in another window, the user manager will let us know\r\n     */\r\n    async _onStorageEvent() {\r\n        if (this._deleted) {\r\n            return;\r\n        }\r\n        const user = await this.assertedPersistence.getCurrentUser();\r\n        if (!this.currentUser && !user) {\r\n            // No change, do nothing (was signed out and remained signed out).\r\n            return;\r\n        }\r\n        // If the same user is to be synchronized.\r\n        if (this.currentUser && user && this.currentUser.uid === user.uid) {\r\n            // Data update, simply copy data changes.\r\n            this._currentUser._assign(user);\r\n            // If tokens changed from previous user tokens, this will trigger\r\n            // notifyAuthListeners_.\r\n            await this.currentUser.getIdToken();\r\n            return;\r\n        }\r\n        // Update current Auth state. Either a new login or logout.\r\n        // Skip blocking callbacks, they should not apply to a change in another tab.\r\n        await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\r\n    }\r\n    async initializeCurrentUser(popupRedirectResolver) {\r\n        var _a;\r\n        // First check to see if we have a pending redirect event.\r\n        const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());\r\n        let futureCurrentUser = previouslyStoredUser;\r\n        let needsTocheckMiddleware = false;\r\n        if (popupRedirectResolver && this.config.authDomain) {\r\n            await this.getOrInitRedirectPersistenceManager();\r\n            const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;\r\n            const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;\r\n            const result = await this.tryRedirectSignIn(popupRedirectResolver);\r\n            // If the stored user (i.e. the old \"currentUser\") has a redirectId that\r\n            // matches the redirect user, then we want to initially sign in with the\r\n            // new user object from result.\r\n            // TODO(samgho): More thoroughly test all of this\r\n            if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\r\n                (result === null || result === void 0 ? void 0 : result.user)) {\r\n                futureCurrentUser = result.user;\r\n                needsTocheckMiddleware = true;\r\n            }\r\n        }\r\n        // If no user in persistence, there is no current user. Set to null.\r\n        if (!futureCurrentUser) {\r\n            return this.directlySetCurrentUser(null);\r\n        }\r\n        if (!futureCurrentUser._redirectEventId) {\r\n            // This isn't a redirect link operation, we can reload and bail.\r\n            // First though, ensure that we check the middleware is happy.\r\n            if (needsTocheckMiddleware) {\r\n                try {\r\n                    await this.beforeStateQueue.runMiddleware(futureCurrentUser);\r\n                }\r\n                catch (e) {\r\n                    futureCurrentUser = previouslyStoredUser;\r\n                    // We know this is available since the bit is only set when the\r\n                    // resolver is available\r\n                    this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));\r\n                }\r\n            }\r\n            if (futureCurrentUser) {\r\n                return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n            }\r\n            else {\r\n                return this.directlySetCurrentUser(null);\r\n            }\r\n        }\r\n        _assert(this._popupRedirectResolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        await this.getOrInitRedirectPersistenceManager();\r\n        // If the redirect user's event ID matches the current user's event ID,\r\n        // DO NOT reload the current user, otherwise they'll be cleared from storage.\r\n        // This is important for the reauthenticateWithRedirect() flow.\r\n        if (this.redirectUser &&\r\n            this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {\r\n            return this.directlySetCurrentUser(futureCurrentUser);\r\n        }\r\n        return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n    }\r\n    async tryRedirectSignIn(redirectResolver) {\r\n        // The redirect user needs to be checked (and signed in if available)\r\n        // during auth initialization. All of the normal sign in and link/reauth\r\n        // flows call back into auth and push things onto the promise queue. We\r\n        // need to await the result of the redirect sign in *inside the promise\r\n        // queue*. This presents a problem: we run into deadlock. See:\r\n        //    ┌> [Initialization] ─────┐\r\n        //    ┌> [<other queue tasks>] │\r\n        //    └─ [getRedirectResult] <─┘\r\n        //    where [] are tasks on the queue and arrows denote awaits\r\n        // Initialization will never complete because it's waiting on something\r\n        // that's waiting for initialization to complete!\r\n        //\r\n        // Instead, this method calls getRedirectResult() (stored in\r\n        // _completeRedirectFn) with an optional parameter that instructs all of\r\n        // the underlying auth operations to skip anything that mutates auth state.\r\n        let result = null;\r\n        try {\r\n            // We know this._popupRedirectResolver is set since redirectResolver\r\n            // is passed in. The _completeRedirectFn expects the unwrapped extern.\r\n            result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);\r\n        }\r\n        catch (e) {\r\n            // Swallow any errors here; the code can retrieve them in\r\n            // getRedirectResult().\r\n            await this._setRedirectUser(null);\r\n        }\r\n        return result;\r\n    }\r\n    async reloadAndSetCurrentUserOrClear(user) {\r\n        try {\r\n            await _reloadWithoutSaving(user);\r\n        }\r\n        catch (e) {\r\n            if ((e === null || e === void 0 ? void 0 : e.code) !==\r\n                `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n                // Something's wrong with the user's token. Log them out and remove\r\n                // them from storage\r\n                return this.directlySetCurrentUser(null);\r\n            }\r\n        }\r\n        return this.directlySetCurrentUser(user);\r\n    }\r\n    useDeviceLanguage() {\r\n        this.languageCode = _getUserLanguage();\r\n    }\r\n    async _delete() {\r\n        this._deleted = true;\r\n    }\r\n    async updateCurrentUser(userExtern) {\r\n        // The public updateCurrentUser method needs to make a copy of the user,\r\n        // and also check that the project matches\r\n        const user = userExtern\r\n            ? getModularInstance(userExtern)\r\n            : null;\r\n        if (user) {\r\n            _assert(user.auth.config.apiKey === this.config.apiKey, this, \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */);\r\n        }\r\n        return this._updateCurrentUser(user && user._clone(this));\r\n    }\r\n    async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {\r\n        if (this._deleted) {\r\n            return;\r\n        }\r\n        if (user) {\r\n            _assert(this.tenantId === user.tenantId, this, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n        }\r\n        if (!skipBeforeStateCallbacks) {\r\n            await this.beforeStateQueue.runMiddleware(user);\r\n        }\r\n        return this.queue(async () => {\r\n            await this.directlySetCurrentUser(user);\r\n            this.notifyAuthListeners();\r\n        });\r\n    }\r\n    async signOut() {\r\n        // Run first, to block _setRedirectUser() if any callbacks fail.\r\n        await this.beforeStateQueue.runMiddleware(null);\r\n        // Clear the redirect user when signOut is called\r\n        if (this.redirectPersistenceManager || this._popupRedirectResolver) {\r\n            await this._setRedirectUser(null);\r\n        }\r\n        // Prevent callbacks from being called again in _updateCurrentUser, as\r\n        // they were already called in the first line.\r\n        return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\r\n    }\r\n    setPersistence(persistence) {\r\n        return this.queue(async () => {\r\n            await this.assertedPersistence.setPersistence(_getInstance(persistence));\r\n        });\r\n    }\r\n    async initializeRecaptchaConfig() {\r\n        const response = await getRecaptchaConfig(this, {\r\n            clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n            version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n        });\r\n        const config = new RecaptchaConfig(response);\r\n        if (this.tenantId == null) {\r\n            this._agentRecaptchaConfig = config;\r\n        }\r\n        else {\r\n            this._tenantRecaptchaConfigs[this.tenantId] = config;\r\n        }\r\n        if (config.emailPasswordEnabled) {\r\n            const verifier = new RecaptchaEnterpriseVerifier(this);\r\n            void verifier.verify();\r\n        }\r\n    }\r\n    _getRecaptchaConfig() {\r\n        if (this.tenantId == null) {\r\n            return this._agentRecaptchaConfig;\r\n        }\r\n        else {\r\n            return this._tenantRecaptchaConfigs[this.tenantId];\r\n        }\r\n    }\r\n    _getPersistence() {\r\n        return this.assertedPersistence.persistence.type;\r\n    }\r\n    _updateErrorMap(errorMap) {\r\n        this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());\r\n    }\r\n    onAuthStateChanged(nextOrObserver, error, completed) {\r\n        return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);\r\n    }\r\n    beforeAuthStateChanged(callback, onAbort) {\r\n        return this.beforeStateQueue.pushCallback(callback, onAbort);\r\n    }\r\n    onIdTokenChanged(nextOrObserver, error, completed) {\r\n        return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);\r\n    }\r\n    authStateReady() {\r\n        return new Promise((resolve, reject) => {\r\n            if (this.currentUser) {\r\n                resolve();\r\n            }\r\n            else {\r\n                const unsubscribe = this.onAuthStateChanged(() => {\r\n                    unsubscribe();\r\n                    resolve();\r\n                }, reject);\r\n            }\r\n        });\r\n    }\r\n    toJSON() {\r\n        var _a;\r\n        return {\r\n            apiKey: this.config.apiKey,\r\n            authDomain: this.config.authDomain,\r\n            appName: this.name,\r\n            currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()\r\n        };\r\n    }\r\n    async _setRedirectUser(user, popupRedirectResolver) {\r\n        const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);\r\n        return user === null\r\n            ? redirectManager.removeCurrentUser()\r\n            : redirectManager.setCurrentUser(user);\r\n    }\r\n    async getOrInitRedirectPersistenceManager(popupRedirectResolver) {\r\n        if (!this.redirectPersistenceManager) {\r\n            const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\r\n                this._popupRedirectResolver;\r\n            _assert(resolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n            this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], \"redirectUser\" /* KeyName.REDIRECT_USER */);\r\n            this.redirectUser =\r\n                await this.redirectPersistenceManager.getCurrentUser();\r\n        }\r\n        return this.redirectPersistenceManager;\r\n    }\r\n    async _redirectUserForId(id) {\r\n        var _a, _b;\r\n        // Make sure we've cleared any pending persistence actions if we're not in\r\n        // the initializer\r\n        if (this._isInitialized) {\r\n            await this.queue(async () => { });\r\n        }\r\n        if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {\r\n            return this._currentUser;\r\n        }\r\n        if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {\r\n            return this.redirectUser;\r\n        }\r\n        return null;\r\n    }\r\n    async _persistUserIfCurrent(user) {\r\n        if (user === this.currentUser) {\r\n            return this.queue(async () => this.directlySetCurrentUser(user));\r\n        }\r\n    }\r\n    /** Notifies listeners only if the user is current */\r\n    _notifyListenersIfCurrent(user) {\r\n        if (user === this.currentUser) {\r\n            this.notifyAuthListeners();\r\n        }\r\n    }\r\n    _key() {\r\n        return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\r\n    }\r\n    _startProactiveRefresh() {\r\n        this.isProactiveRefreshEnabled = true;\r\n        if (this.currentUser) {\r\n            this._currentUser._startProactiveRefresh();\r\n        }\r\n    }\r\n    _stopProactiveRefresh() {\r\n        this.isProactiveRefreshEnabled = false;\r\n        if (this.currentUser) {\r\n            this._currentUser._stopProactiveRefresh();\r\n        }\r\n    }\r\n    /** Returns the current user cast as the internal type */\r\n    get _currentUser() {\r\n        return this.currentUser;\r\n    }\r\n    notifyAuthListeners() {\r\n        var _a, _b;\r\n        if (!this._isInitialized) {\r\n            return;\r\n        }\r\n        this.idTokenSubscription.next(this.currentUser);\r\n        const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;\r\n        if (this.lastNotifiedUid !== currentUid) {\r\n            this.lastNotifiedUid = currentUid;\r\n            this.authStateSubscription.next(this.currentUser);\r\n        }\r\n    }\r\n    registerStateListener(subscription, nextOrObserver, error, completed) {\r\n        if (this._deleted) {\r\n            return () => { };\r\n        }\r\n        const cb = typeof nextOrObserver === 'function'\r\n            ? nextOrObserver\r\n            : nextOrObserver.next.bind(nextOrObserver);\r\n        const promise = this._isInitialized\r\n            ? Promise.resolve()\r\n            : this._initializationPromise;\r\n        _assert(promise, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        // The callback needs to be called asynchronously per the spec.\r\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n        promise.then(() => cb(this.currentUser));\r\n        if (typeof nextOrObserver === 'function') {\r\n            return subscription.addObserver(nextOrObserver, error, completed);\r\n        }\r\n        else {\r\n            return subscription.addObserver(nextOrObserver);\r\n        }\r\n    }\r\n    /**\r\n     * Unprotected (from race conditions) method to set the current user. This\r\n     * should only be called from within a queued callback. This is necessary\r\n     * because the queue shouldn't rely on another queued callback.\r\n     */\r\n    async directlySetCurrentUser(user) {\r\n        if (this.currentUser && this.currentUser !== user) {\r\n            this._currentUser._stopProactiveRefresh();\r\n        }\r\n        if (user && this.isProactiveRefreshEnabled) {\r\n            user._startProactiveRefresh();\r\n        }\r\n        this.currentUser = user;\r\n        if (user) {\r\n            await this.assertedPersistence.setCurrentUser(user);\r\n        }\r\n        else {\r\n            await this.assertedPersistence.removeCurrentUser();\r\n        }\r\n    }\r\n    queue(action) {\r\n        // In case something errors, the callback still should be called in order\r\n        // to keep the promise chain alive\r\n        this.operations = this.operations.then(action, action);\r\n        return this.operations;\r\n    }\r\n    get assertedPersistence() {\r\n        _assert(this.persistenceManager, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        return this.persistenceManager;\r\n    }\r\n    _logFramework(framework) {\r\n        if (!framework || this.frameworks.includes(framework)) {\r\n            return;\r\n        }\r\n        this.frameworks.push(framework);\r\n        // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\r\n        // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\r\n        this.frameworks.sort();\r\n        this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());\r\n    }\r\n    _getFrameworks() {\r\n        return this.frameworks;\r\n    }\r\n    async _getAdditionalHeaders() {\r\n        var _a;\r\n        // Additional headers on every request\r\n        const headers = {\r\n            [\"X-Client-Version\" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion\r\n        };\r\n        if (this.app.options.appId) {\r\n            headers[\"X-Firebase-gmpid\" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;\r\n        }\r\n        // If the heartbeat service exists, add the heartbeat string\r\n        const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider\r\n            .getImmediate({\r\n            optional: true\r\n        })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());\r\n        if (heartbeatsHeader) {\r\n            headers[\"X-Firebase-Client\" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;\r\n        }\r\n        // If the App Check service exists, add the App Check token in the headers\r\n        const appCheckToken = await this._getAppCheckToken();\r\n        if (appCheckToken) {\r\n            headers[\"X-Firebase-AppCheck\" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;\r\n        }\r\n        return headers;\r\n    }\r\n    async _getAppCheckToken() {\r\n        var _a;\r\n        const appCheckTokenResult = await ((_a = this.appCheckServiceProvider\r\n            .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken());\r\n        if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {\r\n            // Context: appCheck.getToken() will never throw even if an error happened.\r\n            // In the error case, a dummy token will be returned along with an error field describing\r\n            // the error. In general, we shouldn't care about the error condition and just use\r\n            // the token (actual or dummy) to send requests.\r\n            _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);\r\n        }\r\n        return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token;\r\n    }\r\n}\r\n/**\r\n * Method to be used to cast down to our private implmentation of Auth.\r\n * It will also handle unwrapping from the compat type if necessary\r\n *\r\n * @param auth Auth object passed in from developer\r\n */\r\nfunction _castAuth(auth) {\r\n    return getModularInstance(auth);\r\n}\r\n/** Helper class to wrap subscriber logic */\r\nclass Subscription {\r\n    constructor(auth) {\r\n        this.auth = auth;\r\n        this.observer = null;\r\n        this.addObserver = createSubscribe(observer => (this.observer = observer));\r\n    }\r\n    get next() {\r\n        _assert(this.observer, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        return this.observer.next.bind(this.observer);\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Initializes an {@link Auth} instance with fine-grained control over\r\n * {@link Dependencies}.\r\n *\r\n * @remarks\r\n *\r\n * This function allows more control over the {@link Auth} instance than\r\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\r\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\r\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\r\n * need control over which persistence layer is used, or to minimize bundle\r\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\r\n *\r\n * For example, if your app only uses anonymous accounts and you only want\r\n * accounts saved for the current session, initialize `Auth` with:\r\n *\r\n * ```js\r\n * const auth = initializeAuth(app, {\r\n *   persistence: browserSessionPersistence,\r\n *   popupRedirectResolver: undefined,\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nfunction initializeAuth(app, deps) {\r\n    const provider = _getProvider(app, 'auth');\r\n    if (provider.isInitialized()) {\r\n        const auth = provider.getImmediate();\r\n        const initialOptions = provider.getOptions();\r\n        if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {\r\n            return auth;\r\n        }\r\n        else {\r\n            _fail(auth, \"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */);\r\n        }\r\n    }\r\n    const auth = provider.initialize({ options: deps });\r\n    return auth;\r\n}\r\nfunction _initializeAuthInstance(auth, deps) {\r\n    const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];\r\n    const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);\r\n    if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {\r\n        auth._updateErrorMap(deps.errorMap);\r\n    }\r\n    // This promise is intended to float; auth initialization happens in the\r\n    // background, meanwhile the auth object may be used by the app.\r\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n    auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);\r\n}\n\n/**\r\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\r\n * Firebase Auth services.\r\n *\r\n * @remarks\r\n * This must be called synchronously immediately following the first call to\r\n * {@link initializeAuth}.  Do not use with production credentials as emulator\r\n * traffic is not encrypted.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\r\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\r\n * `true` to disable the warning banner attached to the DOM.\r\n *\r\n * @public\r\n */\r\nfunction connectAuthEmulator(auth, url, options) {\r\n    const authInternal = _castAuth(auth);\r\n    _assert(authInternal._canInitEmulator, authInternal, \"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);\r\n    _assert(/^https?:\\/\\//.test(url), authInternal, \"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);\r\n    const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);\r\n    const protocol = extractProtocol(url);\r\n    const { host, port } = extractHostAndPort(url);\r\n    const portStr = port === null ? '' : `:${port}`;\r\n    // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\r\n    authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\r\n    authInternal.settings.appVerificationDisabledForTesting = true;\r\n    authInternal.emulatorConfig = Object.freeze({\r\n        host,\r\n        port,\r\n        protocol: protocol.replace(':', ''),\r\n        options: Object.freeze({ disableWarnings })\r\n    });\r\n    if (!disableWarnings) {\r\n        emitEmulatorWarning();\r\n    }\r\n}\r\nfunction extractProtocol(url) {\r\n    const protocolEnd = url.indexOf(':');\r\n    return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\r\n}\r\nfunction extractHostAndPort(url) {\r\n    const protocol = extractProtocol(url);\r\n    const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\r\n    if (!authority) {\r\n        return { host: '', port: null };\r\n    }\r\n    const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\r\n    const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\r\n    if (bracketedIPv6) {\r\n        const host = bracketedIPv6[1];\r\n        return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\r\n    }\r\n    else {\r\n        const [host, port] = hostAndPort.split(':');\r\n        return { host, port: parsePort(port) };\r\n    }\r\n}\r\nfunction parsePort(portStr) {\r\n    if (!portStr) {\r\n        return null;\r\n    }\r\n    const port = Number(portStr);\r\n    if (isNaN(port)) {\r\n        return null;\r\n    }\r\n    return port;\r\n}\r\nfunction emitEmulatorWarning() {\r\n    function attachBanner() {\r\n        const el = document.createElement('p');\r\n        const sty = el.style;\r\n        el.innerText =\r\n            'Running in emulator mode. Do not use with production credentials.';\r\n        sty.position = 'fixed';\r\n        sty.width = '100%';\r\n        sty.backgroundColor = '#ffffff';\r\n        sty.border = '.1em solid #000000';\r\n        sty.color = '#b50000';\r\n        sty.bottom = '0px';\r\n        sty.left = '0px';\r\n        sty.margin = '0px';\r\n        sty.zIndex = '10000';\r\n        sty.textAlign = 'center';\r\n        el.classList.add('firebase-emulator-warning');\r\n        document.body.appendChild(el);\r\n    }\r\n    if (typeof console !== 'undefined' && typeof console.info === 'function') {\r\n        console.info('WARNING: You are using the Auth Emulator,' +\r\n            ' which is intended for local testing only.  Do not use with' +\r\n            ' production credentials.');\r\n    }\r\n    if (typeof window !== 'undefined' && typeof document !== 'undefined') {\r\n        if (document.readyState === 'loading') {\r\n            window.addEventListener('DOMContentLoaded', attachBanner);\r\n        }\r\n        else {\r\n            attachBanner();\r\n        }\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by an {@link AuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass AuthCredential {\r\n    /** @internal */\r\n    constructor(\r\n    /**\r\n     * The authentication provider ID for the credential.\r\n     *\r\n     * @remarks\r\n     * For example, 'facebook.com', or 'google.com'.\r\n     */\r\n    providerId, \r\n    /**\r\n     * The authentication sign in method for the credential.\r\n     *\r\n     * @remarks\r\n     * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\r\n     * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\r\n     * identifier as returned in {@link fetchSignInMethodsForEmail}.\r\n     */\r\n    signInMethod) {\r\n        this.providerId = providerId;\r\n        this.signInMethod = signInMethod;\r\n    }\r\n    /**\r\n     * Returns a JSON-serializable representation of this object.\r\n     *\r\n     * @returns a JSON-serializable representation of this object.\r\n     */\r\n    toJSON() {\r\n        return debugFail('not implemented');\r\n    }\r\n    /** @internal */\r\n    _getIdTokenResponse(_auth) {\r\n        return debugFail('not implemented');\r\n    }\r\n    /** @internal */\r\n    _linkToIdToken(_auth, _idToken) {\r\n        return debugFail('not implemented');\r\n    }\r\n    /** @internal */\r\n    _getReauthenticationResolver(_auth) {\r\n        return debugFail('not implemented');\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function resetPassword(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:resetPassword\" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function updateEmailPassword(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function applyActionCode$1(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithPassword(auth, request) {\r\n    return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPassword\" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendOobCode(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendOobCode\" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendEmailVerification$1(auth, request) {\r\n    return sendOobCode(auth, request);\r\n}\r\nasync function sendPasswordResetEmail$1(auth, request) {\r\n    return sendOobCode(auth, request);\r\n}\r\nasync function sendSignInLinkToEmail$1(auth, request) {\r\n    return sendOobCode(auth, request);\r\n}\r\nasync function verifyAndChangeEmail(auth, request) {\r\n    return sendOobCode(auth, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithEmailLink$1(auth, request) {\r\n    return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithEmailLinkForLinking(auth, request) {\r\n    return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\r\n * {@link ProviderId}.PASSWORD\r\n *\r\n * @remarks\r\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthCredential extends AuthCredential {\r\n    /** @internal */\r\n    constructor(\r\n    /** @internal */\r\n    _email, \r\n    /** @internal */\r\n    _password, signInMethod, \r\n    /** @internal */\r\n    _tenantId = null) {\r\n        super(\"password\" /* ProviderId.PASSWORD */, signInMethod);\r\n        this._email = _email;\r\n        this._password = _password;\r\n        this._tenantId = _tenantId;\r\n    }\r\n    /** @internal */\r\n    static _fromEmailAndPassword(email, password) {\r\n        return new EmailAuthCredential(email, password, \"password\" /* SignInMethod.EMAIL_PASSWORD */);\r\n    }\r\n    /** @internal */\r\n    static _fromEmailAndCode(email, oobCode, tenantId = null) {\r\n        return new EmailAuthCredential(email, oobCode, \"emailLink\" /* SignInMethod.EMAIL_LINK */, tenantId);\r\n    }\r\n    /** {@inheritdoc AuthCredential.toJSON} */\r\n    toJSON() {\r\n        return {\r\n            email: this._email,\r\n            password: this._password,\r\n            signInMethod: this.signInMethod,\r\n            tenantId: this._tenantId\r\n        };\r\n    }\r\n    /**\r\n     * Static method to deserialize a JSON representation of an object into an {@link  AuthCredential}.\r\n     *\r\n     * @param json - Either `object` or the stringified representation of the object. When string is\r\n     * provided, `JSON.parse` would be called first.\r\n     *\r\n     * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n     */\r\n    static fromJSON(json) {\r\n        const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n        if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {\r\n            if (obj.signInMethod === \"password\" /* SignInMethod.EMAIL_PASSWORD */) {\r\n                return this._fromEmailAndPassword(obj.email, obj.password);\r\n            }\r\n            else if (obj.signInMethod === \"emailLink\" /* SignInMethod.EMAIL_LINK */) {\r\n                return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\r\n            }\r\n        }\r\n        return null;\r\n    }\r\n    /** @internal */\r\n    async _getIdTokenResponse(auth) {\r\n        var _a;\r\n        switch (this.signInMethod) {\r\n            case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n                const request = {\r\n                    returnSecureToken: true,\r\n                    email: this._email,\r\n                    password: this._password,\r\n                    clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n                };\r\n                if ((_a = auth._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {\r\n                    const requestWithRecaptcha = await injectRecaptchaFields(auth, request, \"signInWithPassword\" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */);\r\n                    return signInWithPassword(auth, requestWithRecaptcha);\r\n                }\r\n                else {\r\n                    return signInWithPassword(auth, request).catch(async (error) => {\r\n                        if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n                            console.log('Sign-in with email address and password is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');\r\n                            const requestWithRecaptcha = await injectRecaptchaFields(auth, request, \"signInWithPassword\" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */);\r\n                            return signInWithPassword(auth, requestWithRecaptcha);\r\n                        }\r\n                        else {\r\n                            return Promise.reject(error);\r\n                        }\r\n                    });\r\n                }\r\n            case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n                return signInWithEmailLink$1(auth, {\r\n                    email: this._email,\r\n                    oobCode: this._password\r\n                });\r\n            default:\r\n                _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        }\r\n    }\r\n    /** @internal */\r\n    async _linkToIdToken(auth, idToken) {\r\n        switch (this.signInMethod) {\r\n            case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n                return updateEmailPassword(auth, {\r\n                    idToken,\r\n                    returnSecureToken: true,\r\n                    email: this._email,\r\n                    password: this._password\r\n                });\r\n            case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n                return signInWithEmailLinkForLinking(auth, {\r\n                    idToken,\r\n                    email: this._email,\r\n                    oobCode: this._password\r\n                });\r\n            default:\r\n                _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        }\r\n    }\r\n    /** @internal */\r\n    _getReauthenticationResolver(auth) {\r\n        return this._getIdTokenResponse(auth);\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithIdp(auth, request) {\r\n    return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithIdp\" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI$1 = 'http://localhost';\r\n/**\r\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass OAuthCredential extends AuthCredential {\r\n    constructor() {\r\n        super(...arguments);\r\n        this.pendingToken = null;\r\n    }\r\n    /** @internal */\r\n    static _fromParams(params) {\r\n        const cred = new OAuthCredential(params.providerId, params.signInMethod);\r\n        if (params.idToken || params.accessToken) {\r\n            // OAuth 2 and either ID token or access token.\r\n            if (params.idToken) {\r\n                cred.idToken = params.idToken;\r\n            }\r\n            if (params.accessToken) {\r\n                cred.accessToken = params.accessToken;\r\n            }\r\n            // Add nonce if available and no pendingToken is present.\r\n            if (params.nonce && !params.pendingToken) {\r\n                cred.nonce = params.nonce;\r\n            }\r\n            if (params.pendingToken) {\r\n                cred.pendingToken = params.pendingToken;\r\n            }\r\n        }\r\n        else if (params.oauthToken && params.oauthTokenSecret) {\r\n            // OAuth 1 and OAuth token with token secret\r\n            cred.accessToken = params.oauthToken;\r\n            cred.secret = params.oauthTokenSecret;\r\n        }\r\n        else {\r\n            _fail(\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        }\r\n        return cred;\r\n    }\r\n    /** {@inheritdoc AuthCredential.toJSON}  */\r\n    toJSON() {\r\n        return {\r\n            idToken: this.idToken,\r\n            accessToken: this.accessToken,\r\n            secret: this.secret,\r\n            nonce: this.nonce,\r\n            pendingToken: this.pendingToken,\r\n            providerId: this.providerId,\r\n            signInMethod: this.signInMethod\r\n        };\r\n    }\r\n    /**\r\n     * Static method to deserialize a JSON representation of an object into an\r\n     * {@link  AuthCredential}.\r\n     *\r\n     * @param json - Input can be either Object or the stringified representation of the object.\r\n     * When string is provided, JSON.parse would be called first.\r\n     *\r\n     * @returns If the JSON input does not represent an {@link  AuthCredential}, null is returned.\r\n     */\r\n    static fromJSON(json) {\r\n        const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n        const { providerId, signInMethod } = obj, rest = __rest(obj, [\"providerId\", \"signInMethod\"]);\r\n        if (!providerId || !signInMethod) {\r\n            return null;\r\n        }\r\n        const cred = new OAuthCredential(providerId, signInMethod);\r\n        cred.idToken = rest.idToken || undefined;\r\n        cred.accessToken = rest.accessToken || undefined;\r\n        cred.secret = rest.secret;\r\n        cred.nonce = rest.nonce;\r\n        cred.pendingToken = rest.pendingToken || null;\r\n        return cred;\r\n    }\r\n    /** @internal */\r\n    _getIdTokenResponse(auth) {\r\n        const request = this.buildRequest();\r\n        return signInWithIdp(auth, request);\r\n    }\r\n    /** @internal */\r\n    _linkToIdToken(auth, idToken) {\r\n        const request = this.buildRequest();\r\n        request.idToken = idToken;\r\n        return signInWithIdp(auth, request);\r\n    }\r\n    /** @internal */\r\n    _getReauthenticationResolver(auth) {\r\n        const request = this.buildRequest();\r\n        request.autoCreate = false;\r\n        return signInWithIdp(auth, request);\r\n    }\r\n    buildRequest() {\r\n        const request = {\r\n            requestUri: IDP_REQUEST_URI$1,\r\n            returnSecureToken: true\r\n        };\r\n        if (this.pendingToken) {\r\n            request.pendingToken = this.pendingToken;\r\n        }\r\n        else {\r\n            const postBody = {};\r\n            if (this.idToken) {\r\n                postBody['id_token'] = this.idToken;\r\n            }\r\n            if (this.accessToken) {\r\n                postBody['access_token'] = this.accessToken;\r\n            }\r\n            if (this.secret) {\r\n                postBody['oauth_token_secret'] = this.secret;\r\n            }\r\n            postBody['providerId'] = this.providerId;\r\n            if (this.nonce && !this.pendingToken) {\r\n                postBody['nonce'] = this.nonce;\r\n            }\r\n            request.postBody = querystring(postBody);\r\n        }\r\n        return request;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function sendPhoneVerificationCode(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendVerificationCode\" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithPhoneNumber$1(auth, request) {\r\n    return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function linkWithPhoneNumber$1(auth, request) {\r\n    const response = await _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n    if (response.temporaryProof) {\r\n        throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, response);\r\n    }\r\n    return response;\r\n}\r\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {\r\n    [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */\r\n};\r\nasync function verifyPhoneNumberForExisting(auth, request) {\r\n    const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });\r\n    return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents the credentials returned by {@link PhoneAuthProvider}.\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthCredential extends AuthCredential {\r\n    constructor(params) {\r\n        super(\"phone\" /* ProviderId.PHONE */, \"phone\" /* SignInMethod.PHONE */);\r\n        this.params = params;\r\n    }\r\n    /** @internal */\r\n    static _fromVerification(verificationId, verificationCode) {\r\n        return new PhoneAuthCredential({ verificationId, verificationCode });\r\n    }\r\n    /** @internal */\r\n    static _fromTokenResponse(phoneNumber, temporaryProof) {\r\n        return new PhoneAuthCredential({ phoneNumber, temporaryProof });\r\n    }\r\n    /** @internal */\r\n    _getIdTokenResponse(auth) {\r\n        return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());\r\n    }\r\n    /** @internal */\r\n    _linkToIdToken(auth, idToken) {\r\n        return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));\r\n    }\r\n    /** @internal */\r\n    _getReauthenticationResolver(auth) {\r\n        return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\r\n    }\r\n    /** @internal */\r\n    _makeVerificationRequest() {\r\n        const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;\r\n        if (temporaryProof && phoneNumber) {\r\n            return { temporaryProof, phoneNumber };\r\n        }\r\n        return {\r\n            sessionInfo: verificationId,\r\n            code: verificationCode\r\n        };\r\n    }\r\n    /** {@inheritdoc AuthCredential.toJSON} */\r\n    toJSON() {\r\n        const obj = {\r\n            providerId: this.providerId\r\n        };\r\n        if (this.params.phoneNumber) {\r\n            obj.phoneNumber = this.params.phoneNumber;\r\n        }\r\n        if (this.params.temporaryProof) {\r\n            obj.temporaryProof = this.params.temporaryProof;\r\n        }\r\n        if (this.params.verificationCode) {\r\n            obj.verificationCode = this.params.verificationCode;\r\n        }\r\n        if (this.params.verificationId) {\r\n            obj.verificationId = this.params.verificationId;\r\n        }\r\n        return obj;\r\n    }\r\n    /** Generates a phone credential based on a plain object or a JSON string. */\r\n    static fromJSON(json) {\r\n        if (typeof json === 'string') {\r\n            json = JSON.parse(json);\r\n        }\r\n        const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;\r\n        if (!verificationCode &&\r\n            !verificationId &&\r\n            !phoneNumber &&\r\n            !temporaryProof) {\r\n            return null;\r\n        }\r\n        return new PhoneAuthCredential({\r\n            verificationId,\r\n            verificationCode,\r\n            phoneNumber,\r\n            temporaryProof\r\n        });\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Maps the mode string in action code URL to Action Code Info operation.\r\n *\r\n * @param mode\r\n */\r\nfunction parseMode(mode) {\r\n    switch (mode) {\r\n        case 'recoverEmail':\r\n            return \"RECOVER_EMAIL\" /* ActionCodeOperation.RECOVER_EMAIL */;\r\n        case 'resetPassword':\r\n            return \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */;\r\n        case 'signIn':\r\n            return \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n        case 'verifyEmail':\r\n            return \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */;\r\n        case 'verifyAndChangeEmail':\r\n            return \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;\r\n        case 'revertSecondFactorAddition':\r\n            return \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;\r\n        default:\r\n            return null;\r\n    }\r\n}\r\n/**\r\n * Helper to parse FDL links\r\n *\r\n * @param url\r\n */\r\nfunction parseDeepLink(url) {\r\n    const link = querystringDecode(extractQuerystring(url))['link'];\r\n    // Double link case (automatic redirect).\r\n    const doubleDeepLink = link\r\n        ? querystringDecode(extractQuerystring(link))['deep_link_id']\r\n        : null;\r\n    // iOS custom scheme links.\r\n    const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];\r\n    const iOSDoubleDeepLink = iOSDeepLink\r\n        ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\r\n        : null;\r\n    return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\r\n}\r\n/**\r\n * A utility class to parse email action URLs such as password reset, email verification,\r\n * email link sign in, etc.\r\n *\r\n * @public\r\n */\r\nclass ActionCodeURL {\r\n    /**\r\n     * @param actionLink - The link from which to extract the URL.\r\n     * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n     *\r\n     * @internal\r\n     */\r\n    constructor(actionLink) {\r\n        var _a, _b, _c, _d, _e, _f;\r\n        const searchParams = querystringDecode(extractQuerystring(actionLink));\r\n        const apiKey = (_a = searchParams[\"apiKey\" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;\r\n        const code = (_b = searchParams[\"oobCode\" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;\r\n        const operation = parseMode((_c = searchParams[\"mode\" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);\r\n        // Validate API key, code and mode.\r\n        _assert(apiKey && code && operation, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        this.apiKey = apiKey;\r\n        this.operation = operation;\r\n        this.code = code;\r\n        this.continueUrl = (_d = searchParams[\"continueUrl\" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;\r\n        this.languageCode = (_e = searchParams[\"languageCode\" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;\r\n        this.tenantId = (_f = searchParams[\"tenantId\" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;\r\n    }\r\n    /**\r\n     * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\r\n     * otherwise returns null.\r\n     *\r\n     * @param link  - The email action link string.\r\n     * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n     *\r\n     * @public\r\n     */\r\n    static parseLink(link) {\r\n        const actionLink = parseDeepLink(link);\r\n        try {\r\n            return new ActionCodeURL(actionLink);\r\n        }\r\n        catch (_a) {\r\n            return null;\r\n        }\r\n    }\r\n}\r\n/**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if\r\n * the link is valid, otherwise returns null.\r\n *\r\n * @public\r\n */\r\nfunction parseActionCodeURL(link) {\r\n    return ActionCodeURL.parseLink(link);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating {@link EmailAuthCredential}.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthProvider {\r\n    constructor() {\r\n        /**\r\n         * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n         */\r\n        this.providerId = EmailAuthProvider.PROVIDER_ID;\r\n    }\r\n    /**\r\n     * Initialize an {@link AuthCredential} using an email and password.\r\n     *\r\n     * @example\r\n     * ```javascript\r\n     * const authCredential = EmailAuthProvider.credential(email, password);\r\n     * const userCredential = await signInWithCredential(auth, authCredential);\r\n     * ```\r\n     *\r\n     * @example\r\n     * ```javascript\r\n     * const userCredential = await signInWithEmailAndPassword(auth, email, password);\r\n     * ```\r\n     *\r\n     * @param email - Email address.\r\n     * @param password - User account password.\r\n     * @returns The auth provider credential.\r\n     */\r\n    static credential(email, password) {\r\n        return EmailAuthCredential._fromEmailAndPassword(email, password);\r\n    }\r\n    /**\r\n     * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\r\n     * email link operation.\r\n     *\r\n     * @example\r\n     * ```javascript\r\n     * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\r\n     * const userCredential = await signInWithCredential(auth, authCredential);\r\n     * ```\r\n     *\r\n     * @example\r\n     * ```javascript\r\n     * await sendSignInLinkToEmail(auth, email);\r\n     * // Obtain emailLink from user.\r\n     * const userCredential = await signInWithEmailLink(auth, email, emailLink);\r\n     * ```\r\n     *\r\n     * @param auth - The {@link Auth} instance used to verify the link.\r\n     * @param email - Email address.\r\n     * @param emailLink - Sign-in email link.\r\n     * @returns - The auth provider credential.\r\n     */\r\n    static credentialWithLink(email, emailLink) {\r\n        const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n        _assert(actionCodeUrl, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);\r\n    }\r\n}\r\n/**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\nEmailAuthProvider.PROVIDER_ID = \"password\" /* ProviderId.PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\r\n */\r\nEmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = \"password\" /* SignInMethod.EMAIL_PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_LINK.\r\n */\r\nEmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = \"emailLink\" /* SignInMethod.EMAIL_LINK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\r\n *\r\n * This class is not meant to be instantiated directly.\r\n *\r\n * @public\r\n */\r\nclass FederatedAuthProvider {\r\n    /**\r\n     * Constructor for generic OAuth providers.\r\n     *\r\n     * @param providerId - Provider for which credentials should be generated.\r\n     */\r\n    constructor(providerId) {\r\n        this.providerId = providerId;\r\n        /** @internal */\r\n        this.defaultLanguageCode = null;\r\n        /** @internal */\r\n        this.customParameters = {};\r\n    }\r\n    /**\r\n     * Set the language gode.\r\n     *\r\n     * @param languageCode - language code\r\n     */\r\n    setDefaultLanguage(languageCode) {\r\n        this.defaultLanguageCode = languageCode;\r\n    }\r\n    /**\r\n     * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\r\n     * operations.\r\n     *\r\n     * @remarks\r\n     * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\r\n     * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\r\n     *\r\n     * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\r\n     */\r\n    setCustomParameters(customOAuthParameters) {\r\n        this.customParameters = customOAuthParameters;\r\n        return this;\r\n    }\r\n    /**\r\n     * Retrieve the current list of {@link CustomParameters}.\r\n     */\r\n    getCustomParameters() {\r\n        return this.customParameters;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Common code to all OAuth providers. This is separate from the\r\n * {@link OAuthProvider} so that child providers (like\r\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\r\n * Instead, they rely on a static `credential` method.\r\n */\r\nclass BaseOAuthProvider extends FederatedAuthProvider {\r\n    constructor() {\r\n        super(...arguments);\r\n        /** @internal */\r\n        this.scopes = [];\r\n    }\r\n    /**\r\n     * Add an OAuth scope to the credential.\r\n     *\r\n     * @param scope - Provider OAuth scope to add.\r\n     */\r\n    addScope(scope) {\r\n        // If not already added, add scope to list.\r\n        if (!this.scopes.includes(scope)) {\r\n            this.scopes.push(scope);\r\n        }\r\n        return this;\r\n    }\r\n    /**\r\n     * Retrieve the current list of OAuth scopes.\r\n     */\r\n    getScopes() {\r\n        return [...this.scopes];\r\n    }\r\n}\r\n/**\r\n * Provider for generating generic {@link OAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new OAuthProvider('google.com');\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n *   // This is the signed-in user\r\n *   const user = result.user;\r\n *   // This gives you a OAuth Access Token for the provider.\r\n *   const credential = provider.credentialFromResult(auth, result);\r\n *   const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new OAuthProvider('google.com');\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass OAuthProvider extends BaseOAuthProvider {\r\n    /**\r\n     * Creates an {@link OAuthCredential} from a JSON string or a plain object.\r\n     * @param json - A plain object or a JSON string\r\n     */\r\n    static credentialFromJSON(json) {\r\n        const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n        _assert('providerId' in obj && 'signInMethod' in obj, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        return OAuthCredential._fromParams(obj);\r\n    }\r\n    /**\r\n     * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\r\n     *\r\n     * @remarks\r\n     * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\r\n     * the raw nonce must match the nonce field in the ID token.\r\n     *\r\n     * @example\r\n     * ```javascript\r\n     * // `googleUser` from the onsuccess Google Sign In callback.\r\n     * // Initialize a generate OAuth provider with a `google.com` providerId.\r\n     * const provider = new OAuthProvider('google.com');\r\n     * const credential = provider.credential({\r\n     *   idToken: googleUser.getAuthResponse().id_token,\r\n     * });\r\n     * const result = await signInWithCredential(credential);\r\n     * ```\r\n     *\r\n     * @param params - Either the options object containing the ID token, access token and raw nonce\r\n     * or the ID token string.\r\n     */\r\n    credential(params) {\r\n        return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));\r\n    }\r\n    /** An internal credential method that accepts more permissive options */\r\n    _credential(params) {\r\n        _assert(params.idToken || params.accessToken, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        // For OAuthCredential, sign in method is same as providerId.\r\n        return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromResult(userCredential) {\r\n        return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n     * thrown during a sign-in, link, or reauthenticate operation.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromError(error) {\r\n        return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));\r\n    }\r\n    static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n        if (!tokenResponse) {\r\n            return null;\r\n        }\r\n        const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;\r\n        if (!oauthAccessToken &&\r\n            !oauthTokenSecret &&\r\n            !oauthIdToken &&\r\n            !pendingToken) {\r\n            return null;\r\n        }\r\n        if (!providerId) {\r\n            return null;\r\n        }\r\n        try {\r\n            return new OAuthProvider(providerId)._credential({\r\n                idToken: oauthIdToken,\r\n                accessToken: oauthAccessToken,\r\n                nonce,\r\n                pendingToken\r\n            });\r\n        }\r\n        catch (e) {\r\n            return null;\r\n        }\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('user_birthday');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n *   // This is the signed-in user\r\n *   const user = result.user;\r\n *   // This gives you a Facebook Access Token.\r\n *   const credential = FacebookAuthProvider.credentialFromResult(result);\r\n *   const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * provider.addScope('user_birthday');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass FacebookAuthProvider extends BaseOAuthProvider {\r\n    constructor() {\r\n        super(\"facebook.com\" /* ProviderId.FACEBOOK */);\r\n    }\r\n    /**\r\n     * Creates a credential for Facebook.\r\n     *\r\n     * @example\r\n     * ```javascript\r\n     * // `event` from the Facebook auth.authResponseChange callback.\r\n     * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\r\n     * const result = await signInWithCredential(credential);\r\n     * ```\r\n     *\r\n     * @param accessToken - Facebook access token.\r\n     */\r\n    static credential(accessToken) {\r\n        return OAuthCredential._fromParams({\r\n            providerId: FacebookAuthProvider.PROVIDER_ID,\r\n            signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\r\n            accessToken\r\n        });\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromResult(userCredential) {\r\n        return FacebookAuthProvider.credentialFromTaggedObject(userCredential);\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n     * thrown during a sign-in, link, or reauthenticate operation.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromError(error) {\r\n        return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n    }\r\n    static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n        if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n            return null;\r\n        }\r\n        if (!tokenResponse.oauthAccessToken) {\r\n            return null;\r\n        }\r\n        try {\r\n            return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n        }\r\n        catch (_a) {\r\n            return null;\r\n        }\r\n    }\r\n}\r\n/** Always set to {@link SignInMethod}.FACEBOOK. */\r\nFacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = \"facebook.com\" /* SignInMethod.FACEBOOK */;\r\n/** Always set to {@link ProviderId}.FACEBOOK. */\r\nFacebookAuthProvider.PROVIDER_ID = \"facebook.com\" /* ProviderId.FACEBOOK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GoogleAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n *   // This is the signed-in user\r\n *   const user = result.user;\r\n *   // This gives you a Google Access Token.\r\n *   const credential = GoogleAuthProvider.credentialFromResult(result);\r\n *   const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GoogleAuthProvider();\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass GoogleAuthProvider extends BaseOAuthProvider {\r\n    constructor() {\r\n        super(\"google.com\" /* ProviderId.GOOGLE */);\r\n        this.addScope('profile');\r\n    }\r\n    /**\r\n     * Creates a credential for Google. At least one of ID token and access token is required.\r\n     *\r\n     * @example\r\n     * ```javascript\r\n     * // \\`googleUser\\` from the onsuccess Google Sign In callback.\r\n     * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\r\n     * const result = await signInWithCredential(credential);\r\n     * ```\r\n     *\r\n     * @param idToken - Google ID token.\r\n     * @param accessToken - Google access token.\r\n     */\r\n    static credential(idToken, accessToken) {\r\n        return OAuthCredential._fromParams({\r\n            providerId: GoogleAuthProvider.PROVIDER_ID,\r\n            signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\r\n            idToken,\r\n            accessToken\r\n        });\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromResult(userCredential) {\r\n        return GoogleAuthProvider.credentialFromTaggedObject(userCredential);\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n     * thrown during a sign-in, link, or reauthenticate operation.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromError(error) {\r\n        return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n    }\r\n    static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n        if (!tokenResponse) {\r\n            return null;\r\n        }\r\n        const { oauthIdToken, oauthAccessToken } = tokenResponse;\r\n        if (!oauthIdToken && !oauthAccessToken) {\r\n            // This could be an oauth 1 credential or a phone credential\r\n            return null;\r\n        }\r\n        try {\r\n            return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\r\n        }\r\n        catch (_a) {\r\n            return null;\r\n        }\r\n    }\r\n}\r\n/** Always set to {@link SignInMethod}.GOOGLE. */\r\nGoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = \"google.com\" /* SignInMethod.GOOGLE */;\r\n/** Always set to {@link ProviderId}.GOOGLE. */\r\nGoogleAuthProvider.PROVIDER_ID = \"google.com\" /* ProviderId.GOOGLE */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\r\n *\r\n * @remarks\r\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\r\n * the {@link signInWithPopup} handler:\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GithubAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('repo');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n *   // This is the signed-in user\r\n *   const user = result.user;\r\n *   // This gives you a Github Access Token.\r\n *   const credential = GithubAuthProvider.credentialFromResult(result);\r\n *   const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GithubAuthProvider();\r\n * provider.addScope('repo');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass GithubAuthProvider extends BaseOAuthProvider {\r\n    constructor() {\r\n        super(\"github.com\" /* ProviderId.GITHUB */);\r\n    }\r\n    /**\r\n     * Creates a credential for Github.\r\n     *\r\n     * @param accessToken - Github access token.\r\n     */\r\n    static credential(accessToken) {\r\n        return OAuthCredential._fromParams({\r\n            providerId: GithubAuthProvider.PROVIDER_ID,\r\n            signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\r\n            accessToken\r\n        });\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromResult(userCredential) {\r\n        return GithubAuthProvider.credentialFromTaggedObject(userCredential);\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n     * thrown during a sign-in, link, or reauthenticate operation.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromError(error) {\r\n        return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n    }\r\n    static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n        if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n            return null;\r\n        }\r\n        if (!tokenResponse.oauthAccessToken) {\r\n            return null;\r\n        }\r\n        try {\r\n            return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n        }\r\n        catch (_a) {\r\n            return null;\r\n        }\r\n    }\r\n}\r\n/** Always set to {@link SignInMethod}.GITHUB. */\r\nGithubAuthProvider.GITHUB_SIGN_IN_METHOD = \"github.com\" /* SignInMethod.GITHUB */;\r\n/** Always set to {@link ProviderId}.GITHUB. */\r\nGithubAuthProvider.PROVIDER_ID = \"github.com\" /* ProviderId.GITHUB */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI = 'http://localhost';\r\n/**\r\n * @public\r\n */\r\nclass SAMLAuthCredential extends AuthCredential {\r\n    /** @internal */\r\n    constructor(providerId, pendingToken) {\r\n        super(providerId, providerId);\r\n        this.pendingToken = pendingToken;\r\n    }\r\n    /** @internal */\r\n    _getIdTokenResponse(auth) {\r\n        const request = this.buildRequest();\r\n        return signInWithIdp(auth, request);\r\n    }\r\n    /** @internal */\r\n    _linkToIdToken(auth, idToken) {\r\n        const request = this.buildRequest();\r\n        request.idToken = idToken;\r\n        return signInWithIdp(auth, request);\r\n    }\r\n    /** @internal */\r\n    _getReauthenticationResolver(auth) {\r\n        const request = this.buildRequest();\r\n        request.autoCreate = false;\r\n        return signInWithIdp(auth, request);\r\n    }\r\n    /** {@inheritdoc AuthCredential.toJSON}  */\r\n    toJSON() {\r\n        return {\r\n            signInMethod: this.signInMethod,\r\n            providerId: this.providerId,\r\n            pendingToken: this.pendingToken\r\n        };\r\n    }\r\n    /**\r\n     * Static method to deserialize a JSON representation of an object into an\r\n     * {@link  AuthCredential}.\r\n     *\r\n     * @param json - Input can be either Object or the stringified representation of the object.\r\n     * When string is provided, JSON.parse would be called first.\r\n     *\r\n     * @returns If the JSON input does not represent an {@link  AuthCredential}, null is returned.\r\n     */\r\n    static fromJSON(json) {\r\n        const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n        const { providerId, signInMethod, pendingToken } = obj;\r\n        if (!providerId ||\r\n            !signInMethod ||\r\n            !pendingToken ||\r\n            providerId !== signInMethod) {\r\n            return null;\r\n        }\r\n        return new SAMLAuthCredential(providerId, pendingToken);\r\n    }\r\n    /**\r\n     * Helper static method to avoid exposing the constructor to end users.\r\n     *\r\n     * @internal\r\n     */\r\n    static _create(providerId, pendingToken) {\r\n        return new SAMLAuthCredential(providerId, pendingToken);\r\n    }\r\n    buildRequest() {\r\n        return {\r\n            requestUri: IDP_REQUEST_URI,\r\n            returnSecureToken: true,\r\n            pendingToken: this.pendingToken\r\n        };\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SAML_PROVIDER_PREFIX = 'saml.';\r\n/**\r\n * An {@link AuthProvider} for SAML.\r\n *\r\n * @public\r\n */\r\nclass SAMLAuthProvider extends FederatedAuthProvider {\r\n    /**\r\n     * Constructor. The providerId must start with \"saml.\"\r\n     * @param providerId - SAML provider ID.\r\n     */\r\n    constructor(providerId) {\r\n        _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        super(providerId);\r\n    }\r\n    /**\r\n     * Generates an {@link AuthCredential} from a {@link UserCredential} after a\r\n     * successful SAML flow completes.\r\n     *\r\n     * @remarks\r\n     *\r\n     * For example, to get an {@link AuthCredential}, you could write the\r\n     * following code:\r\n     *\r\n     * ```js\r\n     * const userCredential = await signInWithPopup(auth, samlProvider);\r\n     * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\r\n     * ```\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromResult(userCredential) {\r\n        return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n     * thrown during a sign-in, link, or reauthenticate operation.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromError(error) {\r\n        return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));\r\n    }\r\n    /**\r\n     * Creates an {@link AuthCredential} from a JSON string or a plain object.\r\n     * @param json - A plain object or a JSON string\r\n     */\r\n    static credentialFromJSON(json) {\r\n        const credential = SAMLAuthCredential.fromJSON(json);\r\n        _assert(credential, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        return credential;\r\n    }\r\n    static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n        if (!tokenResponse) {\r\n            return null;\r\n        }\r\n        const { pendingToken, providerId } = tokenResponse;\r\n        if (!pendingToken || !providerId) {\r\n            return null;\r\n        }\r\n        try {\r\n            return SAMLAuthCredential._create(providerId, pendingToken);\r\n        }\r\n        catch (e) {\r\n            return null;\r\n        }\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new TwitterAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n *   // This is the signed-in user\r\n *   const user = result.user;\r\n *   // This gives you a Twitter Access Token and Secret.\r\n *   const credential = TwitterAuthProvider.credentialFromResult(result);\r\n *   const token = credential.accessToken;\r\n *   const secret = credential.secret;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new TwitterAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass TwitterAuthProvider extends BaseOAuthProvider {\r\n    constructor() {\r\n        super(\"twitter.com\" /* ProviderId.TWITTER */);\r\n    }\r\n    /**\r\n     * Creates a credential for Twitter.\r\n     *\r\n     * @param token - Twitter access token.\r\n     * @param secret - Twitter secret.\r\n     */\r\n    static credential(token, secret) {\r\n        return OAuthCredential._fromParams({\r\n            providerId: TwitterAuthProvider.PROVIDER_ID,\r\n            signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\r\n            oauthToken: token,\r\n            oauthTokenSecret: secret\r\n        });\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromResult(userCredential) {\r\n        return TwitterAuthProvider.credentialFromTaggedObject(userCredential);\r\n    }\r\n    /**\r\n     * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n     * thrown during a sign-in, link, or reauthenticate operation.\r\n     *\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromError(error) {\r\n        return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n    }\r\n    static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n        if (!tokenResponse) {\r\n            return null;\r\n        }\r\n        const { oauthAccessToken, oauthTokenSecret } = tokenResponse;\r\n        if (!oauthAccessToken || !oauthTokenSecret) {\r\n            return null;\r\n        }\r\n        try {\r\n            return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\r\n        }\r\n        catch (_a) {\r\n            return null;\r\n        }\r\n    }\r\n}\r\n/** Always set to {@link SignInMethod}.TWITTER. */\r\nTwitterAuthProvider.TWITTER_SIGN_IN_METHOD = \"twitter.com\" /* SignInMethod.TWITTER */;\r\n/** Always set to {@link ProviderId}.TWITTER. */\r\nTwitterAuthProvider.PROVIDER_ID = \"twitter.com\" /* ProviderId.TWITTER */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signUp(auth, request) {\r\n    return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserCredentialImpl {\r\n    constructor(params) {\r\n        this.user = params.user;\r\n        this.providerId = params.providerId;\r\n        this._tokenResponse = params._tokenResponse;\r\n        this.operationType = params.operationType;\r\n    }\r\n    static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {\r\n        const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);\r\n        const providerId = providerIdForResponse(idTokenResponse);\r\n        const userCred = new UserCredentialImpl({\r\n            user,\r\n            providerId,\r\n            _tokenResponse: idTokenResponse,\r\n            operationType\r\n        });\r\n        return userCred;\r\n    }\r\n    static async _forOperation(user, operationType, response) {\r\n        await user._updateTokensIfNecessary(response, /* reload */ true);\r\n        const providerId = providerIdForResponse(response);\r\n        return new UserCredentialImpl({\r\n            user,\r\n            providerId,\r\n            _tokenResponse: response,\r\n            operationType\r\n        });\r\n    }\r\n}\r\nfunction providerIdForResponse(response) {\r\n    if (response.providerId) {\r\n        return response.providerId;\r\n    }\r\n    if ('phoneNumber' in response) {\r\n        return \"phone\" /* ProviderId.PHONE */;\r\n    }\r\n    return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in as an anonymous user.\r\n *\r\n * @remarks\r\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\r\n * new anonymous user identity will be created and returned.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nasync function signInAnonymously(auth) {\r\n    var _a;\r\n    const authInternal = _castAuth(auth);\r\n    await authInternal._initializationPromise;\r\n    if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {\r\n        // If an anonymous user is already signed in, no need to sign them in again.\r\n        return new UserCredentialImpl({\r\n            user: authInternal.currentUser,\r\n            providerId: null,\r\n            operationType: \"signIn\" /* OperationType.SIGN_IN */\r\n        });\r\n    }\r\n    const response = await signUp(authInternal, {\r\n        returnSecureToken: true\r\n    });\r\n    const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response, true);\r\n    await authInternal._updateCurrentUser(userCredential.user);\r\n    return userCredential;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorError extends FirebaseError {\r\n    constructor(auth, error, operationType, user) {\r\n        var _a;\r\n        super(error.code, error.message);\r\n        this.operationType = operationType;\r\n        this.user = user;\r\n        // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n        Object.setPrototypeOf(this, MultiFactorError.prototype);\r\n        this.customData = {\r\n            appName: auth.name,\r\n            tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,\r\n            _serverResponse: error.customData._serverResponse,\r\n            operationType\r\n        };\r\n    }\r\n    static _fromErrorAndOperation(auth, error, operationType, user) {\r\n        return new MultiFactorError(auth, error, operationType, user);\r\n    }\r\n}\r\nfunction _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {\r\n    const idTokenProvider = operationType === \"reauthenticate\" /* OperationType.REAUTHENTICATE */\r\n        ? credential._getReauthenticationResolver(auth)\r\n        : credential._getIdTokenResponse(auth);\r\n    return idTokenProvider.catch(error => {\r\n        if (error.code === `auth/${\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */}`) {\r\n            throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);\r\n        }\r\n        throw error;\r\n    });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Takes a set of UserInfo provider data and converts it to a set of names\r\n */\r\nfunction providerDataAsNames(providerData) {\r\n    return new Set(providerData\r\n        .map(({ providerId }) => providerId)\r\n        .filter(pid => !!pid));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Unlinks a provider from a user account.\r\n *\r\n * @param user - The user.\r\n * @param providerId - The provider to unlink.\r\n *\r\n * @public\r\n */\r\nasync function unlink(user, providerId) {\r\n    const userInternal = getModularInstance(user);\r\n    await _assertLinkedStatus(true, userInternal, providerId);\r\n    const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\r\n        idToken: await userInternal.getIdToken(),\r\n        deleteProvider: [providerId]\r\n    });\r\n    const providersLeft = providerDataAsNames(providerUserInfo || []);\r\n    userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));\r\n    if (!providersLeft.has(\"phone\" /* ProviderId.PHONE */)) {\r\n        userInternal.phoneNumber = null;\r\n    }\r\n    await userInternal.auth._persistUserIfCurrent(userInternal);\r\n    return userInternal;\r\n}\r\nasync function _link$1(user, credential, bypassAuthState = false) {\r\n    const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);\r\n    return UserCredentialImpl._forOperation(user, \"link\" /* OperationType.LINK */, response);\r\n}\r\nasync function _assertLinkedStatus(expected, user, provider) {\r\n    await _reloadWithoutSaving(user);\r\n    const providerIds = providerDataAsNames(user.providerData);\r\n    const code = expected === false\r\n        ? \"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */\r\n        : \"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */;\r\n    _assert(providerIds.has(provider) === expected, user.auth, code);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reauthenticate(user, credential, bypassAuthState = false) {\r\n    const { auth } = user;\r\n    const operationType = \"reauthenticate\" /* OperationType.REAUTHENTICATE */;\r\n    try {\r\n        const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);\r\n        _assert(response.idToken, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        const parsed = _parseToken(response.idToken);\r\n        _assert(parsed, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        const { sub: localId } = parsed;\r\n        _assert(user.uid === localId, auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n        return UserCredentialImpl._forOperation(user, operationType, response);\r\n    }\r\n    catch (e) {\r\n        // Convert user deleted error into user mismatch\r\n        if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${\"user-not-found\" /* AuthErrorCode.USER_DELETED */}`) {\r\n            _fail(auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n        }\r\n        throw e;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _signInWithCredential(auth, credential, bypassAuthState = false) {\r\n    const operationType = \"signIn\" /* OperationType.SIGN_IN */;\r\n    const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);\r\n    const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);\r\n    if (!bypassAuthState) {\r\n        await auth._updateCurrentUser(userCredential.user);\r\n    }\r\n    return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCredential(auth, credential) {\r\n    return _signInWithCredential(_castAuth(auth), credential);\r\n}\r\n/**\r\n * Links the user account with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function linkWithCredential(user, credential) {\r\n    const userInternal = getModularInstance(user);\r\n    await _assertLinkedStatus(false, userInternal, credential.providerId);\r\n    return _link$1(userInternal, credential);\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\r\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\r\n * or a `TOKEN_EXPIRED` error.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithCredential(user, credential) {\r\n    return _reauthenticate(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithCustomToken$1(auth, request) {\r\n    return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithCustomToken\" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in using a custom token.\r\n *\r\n * @remarks\r\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\r\n * be generated by an auth backend using the\r\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\r\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\r\n *\r\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param customToken - The custom token to sign in with.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCustomToken(auth, customToken) {\r\n    const authInternal = _castAuth(auth);\r\n    const response = await signInWithCustomToken$1(authInternal, {\r\n        token: customToken,\r\n        returnSecureToken: true\r\n    });\r\n    const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n    await authInternal._updateCurrentUser(cred.user);\r\n    return cred;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorInfoImpl {\r\n    constructor(factorId, response) {\r\n        this.factorId = factorId;\r\n        this.uid = response.mfaEnrollmentId;\r\n        this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\r\n        this.displayName = response.displayName;\r\n    }\r\n    static _fromServerResponse(auth, enrollment) {\r\n        if ('phoneInfo' in enrollment) {\r\n            return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n        }\r\n        else if ('totpInfo' in enrollment) {\r\n            return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n        }\r\n        return _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    }\r\n}\r\nclass PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n    constructor(response) {\r\n        super(\"phone\" /* FactorId.PHONE */, response);\r\n        this.phoneNumber = response.phoneInfo;\r\n    }\r\n    static _fromServerResponse(_auth, enrollment) {\r\n        return new PhoneMultiFactorInfoImpl(enrollment);\r\n    }\r\n}\r\nclass TotpMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n    constructor(response) {\r\n        super(\"totp\" /* FactorId.TOTP */, response);\r\n    }\r\n    static _fromServerResponse(_auth, enrollment) {\r\n        return new TotpMultiFactorInfoImpl(enrollment);\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {\r\n    var _a;\r\n    _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, \"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */);\r\n    _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\r\n        actionCodeSettings.dynamicLinkDomain.length > 0, auth, \"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);\r\n    request.continueUrl = actionCodeSettings.url;\r\n    request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\r\n    request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\r\n    if (actionCodeSettings.iOS) {\r\n        _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, \"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);\r\n        request.iOSBundleId = actionCodeSettings.iOS.bundleId;\r\n    }\r\n    if (actionCodeSettings.android) {\r\n        _assert(actionCodeSettings.android.packageName.length > 0, auth, \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);\r\n        request.androidInstallApp = actionCodeSettings.android.installApp;\r\n        request.androidMinimumVersionCode =\r\n            actionCodeSettings.android.minimumVersion;\r\n        request.androidPackageName = actionCodeSettings.android.packageName;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a password reset email to the given email address.\r\n *\r\n * @remarks\r\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\r\n * the email sent to the user, along with the new password specified by the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n *   url: 'https://www.example.com/?email=user@example.com',\r\n *   iOS: {\r\n *      bundleId: 'com.example.ios'\r\n *   },\r\n *   android: {\r\n *     packageName: 'com.example.android',\r\n *     installApp: true,\r\n *     minimumVersion: '12'\r\n *   },\r\n *   handleCodeInApp: true\r\n * };\r\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain code from user.\r\n * await confirmPasswordReset('user@example.com', code);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendPasswordResetEmail(auth, email, actionCodeSettings) {\r\n    var _a;\r\n    const authInternal = _castAuth(auth);\r\n    const request = {\r\n        requestType: \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */,\r\n        email,\r\n        clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n    };\r\n    if ((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {\r\n        const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, true);\r\n        if (actionCodeSettings) {\r\n            _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);\r\n        }\r\n        await sendPasswordResetEmail$1(authInternal, requestWithRecaptcha);\r\n    }\r\n    else {\r\n        if (actionCodeSettings) {\r\n            _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n        }\r\n        await sendPasswordResetEmail$1(authInternal, request)\r\n            .catch(async (error) => {\r\n            if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n                console.log('Password resets are protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the password reset flow.');\r\n                const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, true);\r\n                if (actionCodeSettings) {\r\n                    _setActionCodeSettingsOnRequest(authInternal, requestWithRecaptcha, actionCodeSettings);\r\n                }\r\n                await sendPasswordResetEmail$1(authInternal, requestWithRecaptcha);\r\n            }\r\n            else {\r\n                return Promise.reject(error);\r\n            }\r\n        });\r\n    }\r\n}\r\n/**\r\n * Completes the password reset process, given a confirmation code and new password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A confirmation code sent to the user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nasync function confirmPasswordReset(auth, oobCode, newPassword) {\r\n    await resetPassword(getModularInstance(auth), {\r\n        oobCode,\r\n        newPassword\r\n    });\r\n    // Do not return the email.\r\n}\r\n/**\r\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function applyActionCode(auth, oobCode) {\r\n    await applyActionCode$1(getModularInstance(auth), { oobCode });\r\n}\r\n/**\r\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns metadata about the code.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function checkActionCode(auth, oobCode) {\r\n    const authModular = getModularInstance(auth);\r\n    const response = await resetPassword(authModular, { oobCode });\r\n    // Email could be empty only if the request type is EMAIL_SIGNIN or\r\n    // VERIFY_AND_CHANGE_EMAIL.\r\n    // New email should not be empty if the request type is\r\n    // VERIFY_AND_CHANGE_EMAIL.\r\n    // Multi-factor info could not be empty if the request type is\r\n    // REVERT_SECOND_FACTOR_ADDITION.\r\n    const operation = response.requestType;\r\n    _assert(operation, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    switch (operation) {\r\n        case \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */:\r\n            break;\r\n        case \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:\r\n            _assert(response.newEmail, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n            break;\r\n        case \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:\r\n            _assert(response.mfaInfo, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        // fall through\r\n        default:\r\n            _assert(response.email, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    }\r\n    // The multi-factor info for revert second factor addition\r\n    let multiFactorInfo = null;\r\n    if (response.mfaInfo) {\r\n        multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);\r\n    }\r\n    return {\r\n        data: {\r\n            email: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n                ? response.newEmail\r\n                : response.email) || null,\r\n            previousEmail: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n                ? response.email\r\n                : response.newEmail) || null,\r\n            multiFactorInfo\r\n        },\r\n        operation\r\n    };\r\n}\r\n/**\r\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns the user's email address if valid.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param code - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function verifyPasswordResetCode(auth, code) {\r\n    const { data } = await checkActionCode(getModularInstance(auth), code);\r\n    // Email should always be present since a code was sent to it\r\n    return data.email;\r\n}\r\n/**\r\n * Creates a new user account associated with the specified email address and password.\r\n *\r\n * @remarks\r\n * On successful creation of the user account, this user will also be signed in to your application.\r\n *\r\n * User account creation can fail if the account already exists or the password is invalid.\r\n *\r\n * Note: The email address acts as a unique identifier for the user and enables an email-based\r\n * password reset. This function will create a new user account and set the initial user password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param password - The user's chosen password.\r\n *\r\n * @public\r\n */\r\nasync function createUserWithEmailAndPassword(auth, email, password) {\r\n    var _a;\r\n    const authInternal = _castAuth(auth);\r\n    const request = {\r\n        returnSecureToken: true,\r\n        email,\r\n        password,\r\n        clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n    };\r\n    let signUpResponse;\r\n    if ((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {\r\n        const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */);\r\n        signUpResponse = signUp(authInternal, requestWithRecaptcha);\r\n    }\r\n    else {\r\n        signUpResponse = signUp(authInternal, request).catch(async (error) => {\r\n            if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n                console.log('Sign-up is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-up flow.');\r\n                const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */);\r\n                return signUp(authInternal, requestWithRecaptcha);\r\n            }\r\n            else {\r\n                return Promise.reject(error);\r\n            }\r\n        });\r\n    }\r\n    const response = await signUpResponse.catch(error => {\r\n        return Promise.reject(error);\r\n    });\r\n    const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n    await authInternal._updateCurrentUser(userCredential.user);\r\n    return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and password.\r\n *\r\n * @remarks\r\n * Fails with an error if the email address and password do not match.\r\n *\r\n * Note: The user's password is NOT the password used to access the user's email account. The\r\n * email address serves as a unique identifier for the user, and the password is used to access\r\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The users email address.\r\n * @param password - The users password.\r\n *\r\n * @public\r\n */\r\nfunction signInWithEmailAndPassword(auth, email, password) {\r\n    return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a sign-in email link to the user with the specified email.\r\n *\r\n * @remarks\r\n * The sign-in operation has to always be completed in the app unlike other out of band email\r\n * actions (password reset and email verifications). This is because, at the end of the flow,\r\n * the user is expected to be signed in and their Auth state persisted within the app.\r\n *\r\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\r\n * address and the email link supplied in the email sent to the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n *   url: 'https://www.example.com/?email=user@example.com',\r\n *   iOS: {\r\n *      bundleId: 'com.example.ios'\r\n *   },\r\n *   android: {\r\n *     packageName: 'com.example.android',\r\n *     installApp: true,\r\n *     minimumVersion: '12'\r\n *   },\r\n *   handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n *   await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param authInternal - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendSignInLinkToEmail(auth, email, actionCodeSettings) {\r\n    var _a;\r\n    const authInternal = _castAuth(auth);\r\n    const request = {\r\n        requestType: \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */,\r\n        email,\r\n        clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n    };\r\n    function setActionCodeSettings(request, actionCodeSettings) {\r\n        _assert(actionCodeSettings.handleCodeInApp, authInternal, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        if (actionCodeSettings) {\r\n            _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n        }\r\n    }\r\n    if ((_a = authInternal._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.emailPasswordEnabled) {\r\n        const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, true);\r\n        setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);\r\n        await sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha);\r\n    }\r\n    else {\r\n        setActionCodeSettings(request, actionCodeSettings);\r\n        await sendSignInLinkToEmail$1(authInternal, request)\r\n            .catch(async (error) => {\r\n            if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n                console.log('Email link sign-in is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.');\r\n                const requestWithRecaptcha = await injectRecaptchaFields(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, true);\r\n                setActionCodeSettings(requestWithRecaptcha, actionCodeSettings);\r\n                await sendSignInLinkToEmail$1(authInternal, requestWithRecaptcha);\r\n            }\r\n            else {\r\n                return Promise.reject(error);\r\n            }\r\n        });\r\n    }\r\n}\r\n/**\r\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nfunction isSignInWithEmailLink(auth, emailLink) {\r\n    const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n    return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and sign-in email link.\r\n *\r\n * @remarks\r\n * If no link is passed, the link is inferred from the current URL.\r\n *\r\n * Fails with an error if the email address is invalid or OTP in email link expires.\r\n *\r\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n *   url: 'https://www.example.com/?email=user@example.com',\r\n *   iOS: {\r\n *      bundleId: 'com.example.ios'\r\n *   },\r\n *   android: {\r\n *     packageName: 'com.example.android',\r\n *     installApp: true,\r\n *     minimumVersion: '12'\r\n *   },\r\n *   handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n *   await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nasync function signInWithEmailLink(auth, email, emailLink) {\r\n    const authModular = getModularInstance(auth);\r\n    const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());\r\n    // Check if the tenant ID in the email link matches the tenant ID on Auth\r\n    // instance.\r\n    _assert(credential._tenantId === (authModular.tenantId || null), authModular, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n    return signInWithCredential(authModular, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createAuthUri(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:createAuthUri\" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Gets the list of possible sign in methods for the given email address.\r\n *\r\n * @remarks\r\n * This is useful to differentiate methods of sign-in for the same provider, eg.\r\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\r\n * {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n *\r\n * @public\r\n */\r\nasync function fetchSignInMethodsForEmail(auth, email) {\r\n    // createAuthUri returns an error if continue URI is not http or https.\r\n    // For environments like Cordova, Chrome extensions, native frameworks, file\r\n    // systems, etc, use http://localhost as continue URL.\r\n    const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\r\n    const request = {\r\n        identifier: email,\r\n        continueUri\r\n    };\r\n    const { signinMethods } = await createAuthUri(getModularInstance(auth), request);\r\n    return signinMethods || [];\r\n}\r\n/**\r\n * Sends a verification email to a user.\r\n *\r\n * @remarks\r\n * The verification process is completed by calling {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n *   url: 'https://www.example.com/?email=user@example.com',\r\n *   iOS: {\r\n *      bundleId: 'com.example.ios'\r\n *   },\r\n *   android: {\r\n *     packageName: 'com.example.android',\r\n *     installApp: true,\r\n *     minimumVersion: '12'\r\n *   },\r\n *   handleCodeInApp: true\r\n * };\r\n * await sendEmailVerification(user, actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendEmailVerification(user, actionCodeSettings) {\r\n    const userInternal = getModularInstance(user);\r\n    const idToken = await user.getIdToken();\r\n    const request = {\r\n        requestType: \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */,\r\n        idToken\r\n    };\r\n    if (actionCodeSettings) {\r\n        _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n    }\r\n    const { email } = await sendEmailVerification$1(userInternal.auth, request);\r\n    if (email !== user.email) {\r\n        await user.reload();\r\n    }\r\n}\r\n/**\r\n * Sends a verification email to a new email address.\r\n *\r\n * @remarks\r\n * The user's email will be updated to the new one after being verified.\r\n *\r\n * If you have a custom email action handler, you can complete the verification process by calling\r\n * {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n *   url: 'https://www.example.com/?email=user@example.com',\r\n *   iOS: {\r\n *      bundleId: 'com.example.ios'\r\n *   },\r\n *   android: {\r\n *     packageName: 'com.example.android',\r\n *     installApp: true,\r\n *     minimumVersion: '12'\r\n *   },\r\n *   handleCodeInApp: true\r\n * };\r\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address to be verified before update.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {\r\n    const userInternal = getModularInstance(user);\r\n    const idToken = await user.getIdToken();\r\n    const request = {\r\n        requestType: \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,\r\n        idToken,\r\n        newEmail\r\n    };\r\n    if (actionCodeSettings) {\r\n        _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n    }\r\n    const { email } = await verifyAndChangeEmail(userInternal.auth, request);\r\n    if (email !== user.email) {\r\n        // If the local copy of the email on user is outdated, reload the\r\n        // user.\r\n        await user.reload();\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateProfile$1(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates a user's profile data.\r\n *\r\n * @param user - The user.\r\n * @param profile - The profile's `displayName` and `photoURL` to update.\r\n *\r\n * @public\r\n */\r\nasync function updateProfile(user, { displayName, photoURL: photoUrl }) {\r\n    if (displayName === undefined && photoUrl === undefined) {\r\n        return;\r\n    }\r\n    const userInternal = getModularInstance(user);\r\n    const idToken = await userInternal.getIdToken();\r\n    const profileRequest = {\r\n        idToken,\r\n        displayName,\r\n        photoUrl,\r\n        returnSecureToken: true\r\n    };\r\n    const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));\r\n    userInternal.displayName = response.displayName || null;\r\n    userInternal.photoURL = response.photoUrl || null;\r\n    // Update the password provider as well\r\n    const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === \"password\" /* ProviderId.PASSWORD */);\r\n    if (passwordProvider) {\r\n        passwordProvider.displayName = userInternal.displayName;\r\n        passwordProvider.photoURL = userInternal.photoURL;\r\n    }\r\n    await userInternal._updateTokensIfNecessary(response);\r\n}\r\n/**\r\n * Updates the user's email address.\r\n *\r\n * @remarks\r\n * An email will be sent to the original email address (if it was set) that allows to revoke the\r\n * email address change, in order to protect them from account hijacking.\r\n *\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address.\r\n *\r\n * @public\r\n */\r\nfunction updateEmail(user, newEmail) {\r\n    return updateEmailOrPassword(getModularInstance(user), newEmail, null);\r\n}\r\n/**\r\n * Updates the user's password.\r\n *\r\n * @remarks\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nfunction updatePassword(user, newPassword) {\r\n    return updateEmailOrPassword(getModularInstance(user), null, newPassword);\r\n}\r\nasync function updateEmailOrPassword(user, email, password) {\r\n    const { auth } = user;\r\n    const idToken = await user.getIdToken();\r\n    const request = {\r\n        idToken,\r\n        returnSecureToken: true\r\n    };\r\n    if (email) {\r\n        request.email = email;\r\n    }\r\n    if (password) {\r\n        request.password = password;\r\n    }\r\n    const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));\r\n    await user._updateTokensIfNecessary(response, /* reload */ true);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Parse the `AdditionalUserInfo` from the ID token response.\r\n *\r\n */\r\nfunction _fromIdTokenResponse(idTokenResponse) {\r\n    var _a, _b;\r\n    if (!idTokenResponse) {\r\n        return null;\r\n    }\r\n    const { providerId } = idTokenResponse;\r\n    const profile = idTokenResponse.rawUserInfo\r\n        ? JSON.parse(idTokenResponse.rawUserInfo)\r\n        : {};\r\n    const isNewUser = idTokenResponse.isNewUser ||\r\n        idTokenResponse.kind === \"identitytoolkit#SignupNewUserResponse\" /* IdTokenResponseKind.SignupNewUser */;\r\n    if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {\r\n        const signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];\r\n        if (signInProvider) {\r\n            const filteredProviderId = signInProvider !== \"anonymous\" /* ProviderId.ANONYMOUS */ &&\r\n                signInProvider !== \"custom\" /* ProviderId.CUSTOM */\r\n                ? signInProvider\r\n                : null;\r\n            // Uses generic class in accordance with the legacy SDK.\r\n            return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\r\n        }\r\n    }\r\n    if (!providerId) {\r\n        return null;\r\n    }\r\n    switch (providerId) {\r\n        case \"facebook.com\" /* ProviderId.FACEBOOK */:\r\n            return new FacebookAdditionalUserInfo(isNewUser, profile);\r\n        case \"github.com\" /* ProviderId.GITHUB */:\r\n            return new GithubAdditionalUserInfo(isNewUser, profile);\r\n        case \"google.com\" /* ProviderId.GOOGLE */:\r\n            return new GoogleAdditionalUserInfo(isNewUser, profile);\r\n        case \"twitter.com\" /* ProviderId.TWITTER */:\r\n            return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);\r\n        case \"custom\" /* ProviderId.CUSTOM */:\r\n        case \"anonymous\" /* ProviderId.ANONYMOUS */:\r\n            return new GenericAdditionalUserInfo(isNewUser, null);\r\n        default:\r\n            return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\r\n    }\r\n}\r\nclass GenericAdditionalUserInfo {\r\n    constructor(isNewUser, providerId, profile = {}) {\r\n        this.isNewUser = isNewUser;\r\n        this.providerId = providerId;\r\n        this.profile = profile;\r\n    }\r\n}\r\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\r\n    constructor(isNewUser, providerId, profile, username) {\r\n        super(isNewUser, providerId, profile);\r\n        this.username = username;\r\n    }\r\n}\r\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n    constructor(isNewUser, profile) {\r\n        super(isNewUser, \"facebook.com\" /* ProviderId.FACEBOOK */, profile);\r\n    }\r\n}\r\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n    constructor(isNewUser, profile) {\r\n        super(isNewUser, \"github.com\" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null);\r\n    }\r\n}\r\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n    constructor(isNewUser, profile) {\r\n        super(isNewUser, \"google.com\" /* ProviderId.GOOGLE */, profile);\r\n    }\r\n}\r\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n    constructor(isNewUser, profile, screenName) {\r\n        super(isNewUser, \"twitter.com\" /* ProviderId.TWITTER */, profile, screenName);\r\n    }\r\n}\r\n/**\r\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\r\n *\r\n * @param userCredential - The user credential.\r\n *\r\n * @public\r\n */\r\nfunction getAdditionalUserInfo(userCredential) {\r\n    const { user, _tokenResponse } = userCredential;\r\n    if (user.isAnonymous && !_tokenResponse) {\r\n        // Handle the special case where signInAnonymously() gets called twice.\r\n        // No network call is made so there's nothing to actually fill this in\r\n        return {\r\n            providerId: null,\r\n            isNewUser: false,\r\n            profile: null\r\n        };\r\n    }\r\n    return _fromIdTokenResponse(_tokenResponse);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Non-optional auth methods.\r\n/**\r\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\r\n * `Auth` session and applies this type of persistence for future sign-in requests, including\r\n * sign-in with redirect requests.\r\n *\r\n * @remarks\r\n * This makes it easy for a user signing in to specify whether their session should be\r\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\r\n * that are shared by other users or have sensitive data.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * setPersistence(auth, browserSessionPersistence);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param persistence - The {@link Persistence} to use.\r\n * @returns A `Promise` that resolves once the persistence change has completed\r\n *\r\n * @public\r\n */\r\nfunction setPersistence(auth, persistence) {\r\n    return getModularInstance(auth).setPersistence(persistence);\r\n}\r\n/**\r\n * Loads the reCAPTCHA configuration into the `Auth` instance.\r\n *\r\n * @remarks\r\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\r\n * verification flow should be triggered for each auth provider, into the\r\n * current Auth session.\r\n *\r\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\r\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\r\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\r\n * auth flows.\r\n *\r\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\r\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * initializeRecaptchaConfig(auth);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction initializeRecaptchaConfig(auth) {\r\n    const authInternal = _castAuth(auth);\r\n    return authInternal.initializeRecaptchaConfig();\r\n}\r\n/**\r\n * Adds an observer for changes to the signed-in user's ID token.\r\n *\r\n * @remarks\r\n * This includes sign-in, sign-out, and token refresh events.\r\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onIdTokenChanged(auth, nextOrObserver, error, completed) {\r\n    return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Adds a blocking callback that runs before an auth state change\r\n * sets a new user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param callback - callback triggered before new user value is set.\r\n *   If this throws, it blocks the user from being set.\r\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\r\n *   callback throws, allowing you to undo any side effects.\r\n */\r\nfunction beforeAuthStateChanged(auth, callback, onAbort) {\r\n    return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\r\n}\r\n/**\r\n * Adds an observer for changes to the user's sign-in state.\r\n *\r\n * @remarks\r\n * To keep the old behavior, see {@link onIdTokenChanged}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onAuthStateChanged(auth, nextOrObserver, error, completed) {\r\n    return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Sets the current language to the default device/browser preference.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction useDeviceLanguage(auth) {\r\n    getModularInstance(auth).useDeviceLanguage();\r\n}\r\n/**\r\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\r\n * {@link Auth} instance.\r\n *\r\n * @remarks\r\n * A new instance copy of the user provided will be made and set as currentUser.\r\n *\r\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\r\n * like other sign in methods.\r\n *\r\n * The operation fails with an error if the user to be updated belongs to a different Firebase\r\n * project.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param user - The new {@link User}.\r\n *\r\n * @public\r\n */\r\nfunction updateCurrentUser(auth, user) {\r\n    return getModularInstance(auth).updateCurrentUser(user);\r\n}\r\n/**\r\n * Signs out the current user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction signOut(auth) {\r\n    return getModularInstance(auth).signOut();\r\n}\r\n/**\r\n * Deletes and signs out the user.\r\n *\r\n * @remarks\r\n * Important: this is a security-sensitive operation that requires the user to have recently\r\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function deleteUser(user) {\r\n    return getModularInstance(user).delete();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorSessionImpl {\r\n    constructor(type, credential, user) {\r\n        this.type = type;\r\n        this.credential = credential;\r\n        this.user = user;\r\n    }\r\n    static _fromIdtoken(idToken, user) {\r\n        return new MultiFactorSessionImpl(\"enroll\" /* MultiFactorSessionType.ENROLL */, idToken, user);\r\n    }\r\n    static _fromMfaPendingCredential(mfaPendingCredential) {\r\n        return new MultiFactorSessionImpl(\"signin\" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);\r\n    }\r\n    toJSON() {\r\n        const key = this.type === \"enroll\" /* MultiFactorSessionType.ENROLL */\r\n            ? 'idToken'\r\n            : 'pendingCredential';\r\n        return {\r\n            multiFactorSession: {\r\n                [key]: this.credential\r\n            }\r\n        };\r\n    }\r\n    static fromJSON(obj) {\r\n        var _a, _b;\r\n        if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {\r\n            if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {\r\n                return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);\r\n            }\r\n            else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {\r\n                return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);\r\n            }\r\n        }\r\n        return null;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorResolverImpl {\r\n    constructor(session, hints, signInResolver) {\r\n        this.session = session;\r\n        this.hints = hints;\r\n        this.signInResolver = signInResolver;\r\n    }\r\n    /** @internal */\r\n    static _fromError(authExtern, error) {\r\n        const auth = _castAuth(authExtern);\r\n        const serverResponse = error.customData._serverResponse;\r\n        const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));\r\n        _assert(serverResponse.mfaPendingCredential, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);\r\n        return new MultiFactorResolverImpl(session, hints, async (assertion) => {\r\n            const mfaResponse = await assertion._process(auth, session);\r\n            // Clear out the unneeded fields from the old login response\r\n            delete serverResponse.mfaInfo;\r\n            delete serverResponse.mfaPendingCredential;\r\n            // Use in the new token & refresh token in the old response\r\n            const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });\r\n            // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\r\n            switch (error.operationType) {\r\n                case \"signIn\" /* OperationType.SIGN_IN */:\r\n                    const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);\r\n                    await auth._updateCurrentUser(userCredential.user);\r\n                    return userCredential;\r\n                case \"reauthenticate\" /* OperationType.REAUTHENTICATE */:\r\n                    _assert(error.user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n                    return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);\r\n                default:\r\n                    _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n            }\r\n        });\r\n    }\r\n    async resolveSignIn(assertionExtern) {\r\n        const assertion = assertionExtern;\r\n        return this.signInResolver(assertion);\r\n    }\r\n}\r\n/**\r\n * Provides a {@link MultiFactorResolver} suitable for completion of a\r\n * multi-factor flow.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\r\n * reauthentication operation.\r\n *\r\n * @public\r\n */\r\nfunction getMultiFactorResolver(auth, error) {\r\n    var _a;\r\n    const authModular = getModularInstance(auth);\r\n    const errorInternal = error;\r\n    _assert(error.customData.operationType, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n    _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n    return MultiFactorResolverImpl._fromError(authModular, errorInternal);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startEnrollPhoneMfa(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollPhoneMfa(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction startEnrollTotpMfa(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollTotpMfa(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction withdrawMfa(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:withdraw\" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));\r\n}\n\nclass MultiFactorUserImpl {\r\n    constructor(user) {\r\n        this.user = user;\r\n        this.enrolledFactors = [];\r\n        user._onReload(userInfo => {\r\n            if (userInfo.mfaInfo) {\r\n                this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));\r\n            }\r\n        });\r\n    }\r\n    static _fromUser(user) {\r\n        return new MultiFactorUserImpl(user);\r\n    }\r\n    async getSession() {\r\n        return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user);\r\n    }\r\n    async enroll(assertionExtern, displayName) {\r\n        const assertion = assertionExtern;\r\n        const session = (await this.getSession());\r\n        const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));\r\n        // New tokens will be issued after enrollment of the new second factors.\r\n        // They need to be updated on the user.\r\n        await this.user._updateTokensIfNecessary(finalizeMfaResponse);\r\n        // The user needs to be reloaded to get the new multi-factor information\r\n        // from server. USER_RELOADED event will be triggered and `enrolledFactors`\r\n        // will be updated.\r\n        return this.user.reload();\r\n    }\r\n    async unenroll(infoOrUid) {\r\n        const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\r\n        const idToken = await this.user.getIdToken();\r\n        try {\r\n            const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {\r\n                idToken,\r\n                mfaEnrollmentId\r\n            }));\r\n            // Remove the second factor from the user's list.\r\n            this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);\r\n            // Depending on whether the backend decided to revoke the user's session,\r\n            // the tokenResponse may be empty. If the tokens were not updated (and they\r\n            // are now invalid), reloading the user will discover this and invalidate\r\n            // the user's state accordingly.\r\n            await this.user._updateTokensIfNecessary(idTokenResponse);\r\n            await this.user.reload();\r\n        }\r\n        catch (e) {\r\n            throw e;\r\n        }\r\n    }\r\n}\r\nconst multiFactorUserCache = new WeakMap();\r\n/**\r\n * The {@link MultiFactorUser} corresponding to the user.\r\n *\r\n * @remarks\r\n * This is used to access all multi-factor properties and operations related to the user.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nfunction multiFactor(user) {\r\n    const userModular = getModularInstance(user);\r\n    if (!multiFactorUserCache.has(userModular)) {\r\n        multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));\r\n    }\r\n    return multiFactorUserCache.get(userModular);\r\n}\n\nconst STORAGE_AVAILABLE_KEY = '__sak';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// There are two different browser persistence types: local and session.\r\n// Both have the same implementation but use a different underlying storage\r\n// object.\r\nclass BrowserPersistenceClass {\r\n    constructor(storageRetriever, type) {\r\n        this.storageRetriever = storageRetriever;\r\n        this.type = type;\r\n    }\r\n    _isAvailable() {\r\n        try {\r\n            if (!this.storage) {\r\n                return Promise.resolve(false);\r\n            }\r\n            this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\r\n            this.storage.removeItem(STORAGE_AVAILABLE_KEY);\r\n            return Promise.resolve(true);\r\n        }\r\n        catch (_a) {\r\n            return Promise.resolve(false);\r\n        }\r\n    }\r\n    _set(key, value) {\r\n        this.storage.setItem(key, JSON.stringify(value));\r\n        return Promise.resolve();\r\n    }\r\n    _get(key) {\r\n        const json = this.storage.getItem(key);\r\n        return Promise.resolve(json ? JSON.parse(json) : null);\r\n    }\r\n    _remove(key) {\r\n        this.storage.removeItem(key);\r\n        return Promise.resolve();\r\n    }\r\n    get storage() {\r\n        return this.storageRetriever();\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _iframeCannotSyncWebStorage() {\r\n    const ua = getUA();\r\n    return _isSafari(ua) || _isIOS(ua);\r\n}\r\n// The polling period in case events are not supported\r\nconst _POLLING_INTERVAL_MS$1 = 1000;\r\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\r\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\r\nclass BrowserLocalPersistence extends BrowserPersistenceClass {\r\n    constructor() {\r\n        super(() => window.localStorage, \"LOCAL\" /* PersistenceType.LOCAL */);\r\n        this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);\r\n        this.listeners = {};\r\n        this.localCache = {};\r\n        // setTimeout return value is platform specific\r\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n        this.pollTimer = null;\r\n        // Safari or iOS browser and embedded in an iframe.\r\n        this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();\r\n        // Whether to use polling instead of depending on window events\r\n        this.fallbackToPolling = _isMobileBrowser();\r\n        this._shouldAllowMigration = true;\r\n    }\r\n    forAllChangedKeys(cb) {\r\n        // Check all keys with listeners on them.\r\n        for (const key of Object.keys(this.listeners)) {\r\n            // Get value from localStorage.\r\n            const newValue = this.storage.getItem(key);\r\n            const oldValue = this.localCache[key];\r\n            // If local map value does not match, trigger listener with storage event.\r\n            // Differentiate this simulated event from the real storage event.\r\n            if (newValue !== oldValue) {\r\n                cb(key, oldValue, newValue);\r\n            }\r\n        }\r\n    }\r\n    onStorageEvent(event, poll = false) {\r\n        // Key would be null in some situations, like when localStorage is cleared\r\n        if (!event.key) {\r\n            this.forAllChangedKeys((key, _oldValue, newValue) => {\r\n                this.notifyListeners(key, newValue);\r\n            });\r\n            return;\r\n        }\r\n        const key = event.key;\r\n        // Check the mechanism how this event was detected.\r\n        // The first event will dictate the mechanism to be used.\r\n        if (poll) {\r\n            // Environment detects storage changes via polling.\r\n            // Remove storage event listener to prevent possible event duplication.\r\n            this.detachListener();\r\n        }\r\n        else {\r\n            // Environment detects storage changes via storage event listener.\r\n            // Remove polling listener to prevent possible event duplication.\r\n            this.stopPolling();\r\n        }\r\n        // Safari embedded iframe. Storage event will trigger with the delta\r\n        // changes but no changes will be applied to the iframe localStorage.\r\n        if (this.safariLocalStorageNotSynced) {\r\n            // Get current iframe page value.\r\n            const storedValue = this.storage.getItem(key);\r\n            // Value not synchronized, synchronize manually.\r\n            if (event.newValue !== storedValue) {\r\n                if (event.newValue !== null) {\r\n                    // Value changed from current value.\r\n                    this.storage.setItem(key, event.newValue);\r\n                }\r\n                else {\r\n                    // Current value deleted.\r\n                    this.storage.removeItem(key);\r\n                }\r\n            }\r\n            else if (this.localCache[key] === event.newValue && !poll) {\r\n                // Already detected and processed, do not trigger listeners again.\r\n                return;\r\n            }\r\n        }\r\n        const triggerListeners = () => {\r\n            // Keep local map up to date in case storage event is triggered before\r\n            // poll.\r\n            const storedValue = this.storage.getItem(key);\r\n            if (!poll && this.localCache[key] === storedValue) {\r\n                // Real storage event which has already been detected, do nothing.\r\n                // This seems to trigger in some IE browsers for some reason.\r\n                return;\r\n            }\r\n            this.notifyListeners(key, storedValue);\r\n        };\r\n        const storedValue = this.storage.getItem(key);\r\n        if (_isIE10() &&\r\n            storedValue !== event.newValue &&\r\n            event.newValue !== event.oldValue) {\r\n            // IE 10 has this weird bug where a storage event would trigger with the\r\n            // correct key, oldValue and newValue but localStorage.getItem(key) does\r\n            // not yield the updated value until a few milliseconds. This ensures\r\n            // this recovers from that situation.\r\n            setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\r\n        }\r\n        else {\r\n            triggerListeners();\r\n        }\r\n    }\r\n    notifyListeners(key, value) {\r\n        this.localCache[key] = value;\r\n        const listeners = this.listeners[key];\r\n        if (listeners) {\r\n            for (const listener of Array.from(listeners)) {\r\n                listener(value ? JSON.parse(value) : value);\r\n            }\r\n        }\r\n    }\r\n    startPolling() {\r\n        this.stopPolling();\r\n        this.pollTimer = setInterval(() => {\r\n            this.forAllChangedKeys((key, oldValue, newValue) => {\r\n                this.onStorageEvent(new StorageEvent('storage', {\r\n                    key,\r\n                    oldValue,\r\n                    newValue\r\n                }), \r\n                /* poll */ true);\r\n            });\r\n        }, _POLLING_INTERVAL_MS$1);\r\n    }\r\n    stopPolling() {\r\n        if (this.pollTimer) {\r\n            clearInterval(this.pollTimer);\r\n            this.pollTimer = null;\r\n        }\r\n    }\r\n    attachListener() {\r\n        window.addEventListener('storage', this.boundEventHandler);\r\n    }\r\n    detachListener() {\r\n        window.removeEventListener('storage', this.boundEventHandler);\r\n    }\r\n    _addListener(key, listener) {\r\n        if (Object.keys(this.listeners).length === 0) {\r\n            // Whether browser can detect storage event when it had already been pushed to the background.\r\n            // This may happen in some mobile browsers. A localStorage change in the foreground window\r\n            // will not be detected in the background window via the storage event.\r\n            // This was detected in iOS 7.x mobile browsers\r\n            if (this.fallbackToPolling) {\r\n                this.startPolling();\r\n            }\r\n            else {\r\n                this.attachListener();\r\n            }\r\n        }\r\n        if (!this.listeners[key]) {\r\n            this.listeners[key] = new Set();\r\n            // Populate the cache to avoid spuriously triggering on first poll.\r\n            this.localCache[key] = this.storage.getItem(key);\r\n        }\r\n        this.listeners[key].add(listener);\r\n    }\r\n    _removeListener(key, listener) {\r\n        if (this.listeners[key]) {\r\n            this.listeners[key].delete(listener);\r\n            if (this.listeners[key].size === 0) {\r\n                delete this.listeners[key];\r\n            }\r\n        }\r\n        if (Object.keys(this.listeners).length === 0) {\r\n            this.detachListener();\r\n            this.stopPolling();\r\n        }\r\n    }\r\n    // Update local cache on base operations:\r\n    async _set(key, value) {\r\n        await super._set(key, value);\r\n        this.localCache[key] = JSON.stringify(value);\r\n    }\r\n    async _get(key) {\r\n        const value = await super._get(key);\r\n        this.localCache[key] = JSON.stringify(value);\r\n        return value;\r\n    }\r\n    async _remove(key) {\r\n        await super._remove(key);\r\n        delete this.localCache[key];\r\n    }\r\n}\r\nBrowserLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserLocalPersistence = BrowserLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass BrowserSessionPersistence extends BrowserPersistenceClass {\r\n    constructor() {\r\n        super(() => window.sessionStorage, \"SESSION\" /* PersistenceType.SESSION */);\r\n    }\r\n    _addListener(_key, _listener) {\r\n        // Listeners are not supported for session storage since it cannot be shared across windows\r\n        return;\r\n    }\r\n    _removeListener(_key, _listener) {\r\n        // Listeners are not supported for session storage since it cannot be shared across windows\r\n        return;\r\n    }\r\n}\r\nBrowserSessionPersistence.type = 'SESSION';\r\n/**\r\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserSessionPersistence = BrowserSessionPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\r\n *\r\n * @param promises - Array of promises to wait on.\r\n */\r\nfunction _allSettled(promises) {\r\n    return Promise.all(promises.map(async (promise) => {\r\n        try {\r\n            const value = await promise;\r\n            return {\r\n                fulfilled: true,\r\n                value\r\n            };\r\n        }\r\n        catch (reason) {\r\n            return {\r\n                fulfilled: false,\r\n                reason\r\n            };\r\n        }\r\n    }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface class for receiving messages.\r\n *\r\n */\r\nclass Receiver {\r\n    constructor(eventTarget) {\r\n        this.eventTarget = eventTarget;\r\n        this.handlersMap = {};\r\n        this.boundEventHandler = this.handleEvent.bind(this);\r\n    }\r\n    /**\r\n     * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\r\n     *\r\n     * @param eventTarget - An event target (such as window or self) through which the underlying\r\n     * messages will be received.\r\n     */\r\n    static _getInstance(eventTarget) {\r\n        // The results are stored in an array since objects can't be keys for other\r\n        // objects. In addition, setting a unique property on an event target as a\r\n        // hash map key may not be allowed due to CORS restrictions.\r\n        const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));\r\n        if (existingInstance) {\r\n            return existingInstance;\r\n        }\r\n        const newInstance = new Receiver(eventTarget);\r\n        this.receivers.push(newInstance);\r\n        return newInstance;\r\n    }\r\n    isListeningto(eventTarget) {\r\n        return this.eventTarget === eventTarget;\r\n    }\r\n    /**\r\n     * Fans out a MessageEvent to the appropriate listeners.\r\n     *\r\n     * @remarks\r\n     * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\r\n     * finished processing.\r\n     *\r\n     * @param event - The MessageEvent.\r\n     *\r\n     */\r\n    async handleEvent(event) {\r\n        const messageEvent = event;\r\n        const { eventId, eventType, data } = messageEvent.data;\r\n        const handlers = this.handlersMap[eventType];\r\n        if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {\r\n            return;\r\n        }\r\n        messageEvent.ports[0].postMessage({\r\n            status: \"ack\" /* _Status.ACK */,\r\n            eventId,\r\n            eventType\r\n        });\r\n        const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));\r\n        const response = await _allSettled(promises);\r\n        messageEvent.ports[0].postMessage({\r\n            status: \"done\" /* _Status.DONE */,\r\n            eventId,\r\n            eventType,\r\n            response\r\n        });\r\n    }\r\n    /**\r\n     * Subscribe an event handler for a particular event.\r\n     *\r\n     * @param eventType - Event name to subscribe to.\r\n     * @param eventHandler - The event handler which should receive the events.\r\n     *\r\n     */\r\n    _subscribe(eventType, eventHandler) {\r\n        if (Object.keys(this.handlersMap).length === 0) {\r\n            this.eventTarget.addEventListener('message', this.boundEventHandler);\r\n        }\r\n        if (!this.handlersMap[eventType]) {\r\n            this.handlersMap[eventType] = new Set();\r\n        }\r\n        this.handlersMap[eventType].add(eventHandler);\r\n    }\r\n    /**\r\n     * Unsubscribe an event handler from a particular event.\r\n     *\r\n     * @param eventType - Event name to unsubscribe from.\r\n     * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\r\n     *\r\n     */\r\n    _unsubscribe(eventType, eventHandler) {\r\n        if (this.handlersMap[eventType] && eventHandler) {\r\n            this.handlersMap[eventType].delete(eventHandler);\r\n        }\r\n        if (!eventHandler || this.handlersMap[eventType].size === 0) {\r\n            delete this.handlersMap[eventType];\r\n        }\r\n        if (Object.keys(this.handlersMap).length === 0) {\r\n            this.eventTarget.removeEventListener('message', this.boundEventHandler);\r\n        }\r\n    }\r\n}\r\nReceiver.receivers = [];\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _generateEventId(prefix = '', digits = 10) {\r\n    let random = '';\r\n    for (let i = 0; i < digits; i++) {\r\n        random += Math.floor(Math.random() * 10);\r\n    }\r\n    return prefix + random;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface for sending messages and waiting for a completion response.\r\n *\r\n */\r\nclass Sender {\r\n    constructor(target) {\r\n        this.target = target;\r\n        this.handlers = new Set();\r\n    }\r\n    /**\r\n     * Unsubscribe the handler and remove it from our tracking Set.\r\n     *\r\n     * @param handler - The handler to unsubscribe.\r\n     */\r\n    removeMessageHandler(handler) {\r\n        if (handler.messageChannel) {\r\n            handler.messageChannel.port1.removeEventListener('message', handler.onMessage);\r\n            handler.messageChannel.port1.close();\r\n        }\r\n        this.handlers.delete(handler);\r\n    }\r\n    /**\r\n     * Send a message to the Receiver located at {@link target}.\r\n     *\r\n     * @remarks\r\n     * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\r\n     * receiver has had a chance to fully process the event.\r\n     *\r\n     * @param eventType - Type of event to send.\r\n     * @param data - The payload of the event.\r\n     * @param timeout - Timeout for waiting on an ACK from the receiver.\r\n     *\r\n     * @returns An array of settled promises from all the handlers that were listening on the receiver.\r\n     */\r\n    async _send(eventType, data, timeout = 50 /* _TimeoutDuration.ACK */) {\r\n        const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\r\n        if (!messageChannel) {\r\n            throw new Error(\"connection_unavailable\" /* _MessageError.CONNECTION_UNAVAILABLE */);\r\n        }\r\n        // Node timers and browser timers return fundamentally different types.\r\n        // We don't actually care what the value is but TS won't accept unknown and\r\n        // we can't cast properly in both environments.\r\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n        let completionTimer;\r\n        let handler;\r\n        return new Promise((resolve, reject) => {\r\n            const eventId = _generateEventId('', 20);\r\n            messageChannel.port1.start();\r\n            const ackTimer = setTimeout(() => {\r\n                reject(new Error(\"unsupported_event\" /* _MessageError.UNSUPPORTED_EVENT */));\r\n            }, timeout);\r\n            handler = {\r\n                messageChannel,\r\n                onMessage(event) {\r\n                    const messageEvent = event;\r\n                    if (messageEvent.data.eventId !== eventId) {\r\n                        return;\r\n                    }\r\n                    switch (messageEvent.data.status) {\r\n                        case \"ack\" /* _Status.ACK */:\r\n                            // The receiver should ACK first.\r\n                            clearTimeout(ackTimer);\r\n                            completionTimer = setTimeout(() => {\r\n                                reject(new Error(\"timeout\" /* _MessageError.TIMEOUT */));\r\n                            }, 3000 /* _TimeoutDuration.COMPLETION */);\r\n                            break;\r\n                        case \"done\" /* _Status.DONE */:\r\n                            // Once the receiver's handlers are finished we will get the results.\r\n                            clearTimeout(completionTimer);\r\n                            resolve(messageEvent.data.response);\r\n                            break;\r\n                        default:\r\n                            clearTimeout(ackTimer);\r\n                            clearTimeout(completionTimer);\r\n                            reject(new Error(\"invalid_response\" /* _MessageError.INVALID_RESPONSE */));\r\n                            break;\r\n                    }\r\n                }\r\n            };\r\n            this.handlers.add(handler);\r\n            messageChannel.port1.addEventListener('message', handler.onMessage);\r\n            this.target.postMessage({\r\n                eventType,\r\n                eventId,\r\n                data\r\n            }, [messageChannel.port2]);\r\n        }).finally(() => {\r\n            if (handler) {\r\n                this.removeMessageHandler(handler);\r\n            }\r\n        });\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Lazy accessor for window, since the compat layer won't tree shake this out,\r\n * we need to make sure not to mess with window unless we have to\r\n */\r\nfunction _window() {\r\n    return window;\r\n}\r\nfunction _setWindowLocation(url) {\r\n    _window().location.href = url;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _isWorker() {\r\n    return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\r\n        typeof _window()['importScripts'] === 'function');\r\n}\r\nasync function _getActiveServiceWorker() {\r\n    if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {\r\n        return null;\r\n    }\r\n    try {\r\n        const registration = await navigator.serviceWorker.ready;\r\n        return registration.active;\r\n    }\r\n    catch (_a) {\r\n        return null;\r\n    }\r\n}\r\nfunction _getServiceWorkerController() {\r\n    var _a;\r\n    return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;\r\n}\r\nfunction _getWorkerGlobalScope() {\r\n    return _isWorker() ? self : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebaseLocalStorageDb';\r\nconst DB_VERSION = 1;\r\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\r\nconst DB_DATA_KEYPATH = 'fbase_key';\r\n/**\r\n * Promise wrapper for IDBRequest\r\n *\r\n * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6\r\n *\r\n */\r\nclass DBPromise {\r\n    constructor(request) {\r\n        this.request = request;\r\n    }\r\n    toPromise() {\r\n        return new Promise((resolve, reject) => {\r\n            this.request.addEventListener('success', () => {\r\n                resolve(this.request.result);\r\n            });\r\n            this.request.addEventListener('error', () => {\r\n                reject(this.request.error);\r\n            });\r\n        });\r\n    }\r\n}\r\nfunction getObjectStore(db, isReadWrite) {\r\n    return db\r\n        .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\r\n        .objectStore(DB_OBJECTSTORE_NAME);\r\n}\r\nfunction _deleteDatabase() {\r\n    const request = indexedDB.deleteDatabase(DB_NAME);\r\n    return new DBPromise(request).toPromise();\r\n}\r\nfunction _openDatabase() {\r\n    const request = indexedDB.open(DB_NAME, DB_VERSION);\r\n    return new Promise((resolve, reject) => {\r\n        request.addEventListener('error', () => {\r\n            reject(request.error);\r\n        });\r\n        request.addEventListener('upgradeneeded', () => {\r\n            const db = request.result;\r\n            try {\r\n                db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\r\n            }\r\n            catch (e) {\r\n                reject(e);\r\n            }\r\n        });\r\n        request.addEventListener('success', async () => {\r\n            const db = request.result;\r\n            // Strange bug that occurs in Firefox when multiple tabs are opened at the\r\n            // same time. The only way to recover seems to be deleting the database\r\n            // and re-initializing it.\r\n            // https://github.com/firebase/firebase-js-sdk/issues/634\r\n            if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\r\n                // Need to close the database or else you get a `blocked` event\r\n                db.close();\r\n                await _deleteDatabase();\r\n                resolve(await _openDatabase());\r\n            }\r\n            else {\r\n                resolve(db);\r\n            }\r\n        });\r\n    });\r\n}\r\nasync function _putObject(db, key, value) {\r\n    const request = getObjectStore(db, true).put({\r\n        [DB_DATA_KEYPATH]: key,\r\n        value\r\n    });\r\n    return new DBPromise(request).toPromise();\r\n}\r\nasync function getObject(db, key) {\r\n    const request = getObjectStore(db, false).get(key);\r\n    const data = await new DBPromise(request).toPromise();\r\n    return data === undefined ? null : data.value;\r\n}\r\nfunction _deleteObject(db, key) {\r\n    const request = getObjectStore(db, true).delete(key);\r\n    return new DBPromise(request).toPromise();\r\n}\r\nconst _POLLING_INTERVAL_MS = 800;\r\nconst _TRANSACTION_RETRY_COUNT = 3;\r\nclass IndexedDBLocalPersistence {\r\n    constructor() {\r\n        this.type = \"LOCAL\" /* PersistenceType.LOCAL */;\r\n        this._shouldAllowMigration = true;\r\n        this.listeners = {};\r\n        this.localCache = {};\r\n        // setTimeout return value is platform specific\r\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n        this.pollTimer = null;\r\n        this.pendingWrites = 0;\r\n        this.receiver = null;\r\n        this.sender = null;\r\n        this.serviceWorkerReceiverAvailable = false;\r\n        this.activeServiceWorker = null;\r\n        // Fire & forget the service worker registration as it may never resolve\r\n        this._workerInitializationPromise =\r\n            this.initializeServiceWorkerMessaging().then(() => { }, () => { });\r\n    }\r\n    async _openDb() {\r\n        if (this.db) {\r\n            return this.db;\r\n        }\r\n        this.db = await _openDatabase();\r\n        return this.db;\r\n    }\r\n    async _withRetries(op) {\r\n        let numAttempts = 0;\r\n        while (true) {\r\n            try {\r\n                const db = await this._openDb();\r\n                return await op(db);\r\n            }\r\n            catch (e) {\r\n                if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\r\n                    throw e;\r\n                }\r\n                if (this.db) {\r\n                    this.db.close();\r\n                    this.db = undefined;\r\n                }\r\n                // TODO: consider adding exponential backoff\r\n            }\r\n        }\r\n    }\r\n    /**\r\n     * IndexedDB events do not propagate from the main window to the worker context.  We rely on a\r\n     * postMessage interface to send these events to the worker ourselves.\r\n     */\r\n    async initializeServiceWorkerMessaging() {\r\n        return _isWorker() ? this.initializeReceiver() : this.initializeSender();\r\n    }\r\n    /**\r\n     * As the worker we should listen to events from the main window.\r\n     */\r\n    async initializeReceiver() {\r\n        this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\r\n        // Refresh from persistence if we receive a KeyChanged message.\r\n        this.receiver._subscribe(\"keyChanged\" /* _EventType.KEY_CHANGED */, async (_origin, data) => {\r\n            const keys = await this._poll();\r\n            return {\r\n                keyProcessed: keys.includes(data.key)\r\n            };\r\n        });\r\n        // Let the sender know that we are listening so they give us more timeout.\r\n        this.receiver._subscribe(\"ping\" /* _EventType.PING */, async (_origin, _data) => {\r\n            return [\"keyChanged\" /* _EventType.KEY_CHANGED */];\r\n        });\r\n    }\r\n    /**\r\n     * As the main window, we should let the worker know when keys change (set and remove).\r\n     *\r\n     * @remarks\r\n     * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\r\n     * may not resolve.\r\n     */\r\n    async initializeSender() {\r\n        var _a, _b;\r\n        // Check to see if there's an active service worker.\r\n        this.activeServiceWorker = await _getActiveServiceWorker();\r\n        if (!this.activeServiceWorker) {\r\n            return;\r\n        }\r\n        this.sender = new Sender(this.activeServiceWorker);\r\n        // Ping the service worker to check what events they can handle.\r\n        const results = await this.sender._send(\"ping\" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */);\r\n        if (!results) {\r\n            return;\r\n        }\r\n        if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&\r\n            ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes(\"keyChanged\" /* _EventType.KEY_CHANGED */))) {\r\n            this.serviceWorkerReceiverAvailable = true;\r\n        }\r\n    }\r\n    /**\r\n     * Let the worker know about a changed key, the exact key doesn't technically matter since the\r\n     * worker will just trigger a full sync anyway.\r\n     *\r\n     * @remarks\r\n     * For now, we only support one service worker per page.\r\n     *\r\n     * @param key - Storage key which changed.\r\n     */\r\n    async notifyServiceWorker(key) {\r\n        if (!this.sender ||\r\n            !this.activeServiceWorker ||\r\n            _getServiceWorkerController() !== this.activeServiceWorker) {\r\n            return;\r\n        }\r\n        try {\r\n            await this.sender._send(\"keyChanged\" /* _EventType.KEY_CHANGED */, { key }, \r\n            // Use long timeout if receiver has previously responded to a ping from us.\r\n            this.serviceWorkerReceiverAvailable\r\n                ? 800 /* _TimeoutDuration.LONG_ACK */\r\n                : 50 /* _TimeoutDuration.ACK */);\r\n        }\r\n        catch (_a) {\r\n            // This is a best effort approach. Ignore errors.\r\n        }\r\n    }\r\n    async _isAvailable() {\r\n        try {\r\n            if (!indexedDB) {\r\n                return false;\r\n            }\r\n            const db = await _openDatabase();\r\n            await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\r\n            await _deleteObject(db, STORAGE_AVAILABLE_KEY);\r\n            return true;\r\n        }\r\n        catch (_a) { }\r\n        return false;\r\n    }\r\n    async _withPendingWrite(write) {\r\n        this.pendingWrites++;\r\n        try {\r\n            await write();\r\n        }\r\n        finally {\r\n            this.pendingWrites--;\r\n        }\r\n    }\r\n    async _set(key, value) {\r\n        return this._withPendingWrite(async () => {\r\n            await this._withRetries((db) => _putObject(db, key, value));\r\n            this.localCache[key] = value;\r\n            return this.notifyServiceWorker(key);\r\n        });\r\n    }\r\n    async _get(key) {\r\n        const obj = (await this._withRetries((db) => getObject(db, key)));\r\n        this.localCache[key] = obj;\r\n        return obj;\r\n    }\r\n    async _remove(key) {\r\n        return this._withPendingWrite(async () => {\r\n            await this._withRetries((db) => _deleteObject(db, key));\r\n            delete this.localCache[key];\r\n            return this.notifyServiceWorker(key);\r\n        });\r\n    }\r\n    async _poll() {\r\n        // TODO: check if we need to fallback if getAll is not supported\r\n        const result = await this._withRetries((db) => {\r\n            const getAllRequest = getObjectStore(db, false).getAll();\r\n            return new DBPromise(getAllRequest).toPromise();\r\n        });\r\n        if (!result) {\r\n            return [];\r\n        }\r\n        // If we have pending writes in progress abort, we'll get picked up on the next poll\r\n        if (this.pendingWrites !== 0) {\r\n            return [];\r\n        }\r\n        const keys = [];\r\n        const keysInResult = new Set();\r\n        for (const { fbase_key: key, value } of result) {\r\n            keysInResult.add(key);\r\n            if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\r\n                this.notifyListeners(key, value);\r\n                keys.push(key);\r\n            }\r\n        }\r\n        for (const localKey of Object.keys(this.localCache)) {\r\n            if (this.localCache[localKey] && !keysInResult.has(localKey)) {\r\n                // Deleted\r\n                this.notifyListeners(localKey, null);\r\n                keys.push(localKey);\r\n            }\r\n        }\r\n        return keys;\r\n    }\r\n    notifyListeners(key, newValue) {\r\n        this.localCache[key] = newValue;\r\n        const listeners = this.listeners[key];\r\n        if (listeners) {\r\n            for (const listener of Array.from(listeners)) {\r\n                listener(newValue);\r\n            }\r\n        }\r\n    }\r\n    startPolling() {\r\n        this.stopPolling();\r\n        this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);\r\n    }\r\n    stopPolling() {\r\n        if (this.pollTimer) {\r\n            clearInterval(this.pollTimer);\r\n            this.pollTimer = null;\r\n        }\r\n    }\r\n    _addListener(key, listener) {\r\n        if (Object.keys(this.listeners).length === 0) {\r\n            this.startPolling();\r\n        }\r\n        if (!this.listeners[key]) {\r\n            this.listeners[key] = new Set();\r\n            // Populate the cache to avoid spuriously triggering on first poll.\r\n            void this._get(key); // This can happen in the background async and we can return immediately.\r\n        }\r\n        this.listeners[key].add(listener);\r\n    }\r\n    _removeListener(key, listener) {\r\n        if (this.listeners[key]) {\r\n            this.listeners[key].delete(listener);\r\n            if (this.listeners[key].size === 0) {\r\n                delete this.listeners[key];\r\n            }\r\n        }\r\n        if (Object.keys(this.listeners).length === 0) {\r\n            this.stopPolling();\r\n        }\r\n    }\r\n}\r\nIndexedDBLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst indexedDBLocalPersistence = IndexedDBLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startSignInPhoneMfa(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:start\" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInPhoneMfa(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInTotpMfa(auth, request) {\r\n    return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _SOLVE_TIME_MS = 500;\r\nconst _EXPIRATION_TIME_MS = 60000;\r\nconst _WIDGET_ID_START = 1000000000000;\r\nclass MockReCaptcha {\r\n    constructor(auth) {\r\n        this.auth = auth;\r\n        this.counter = _WIDGET_ID_START;\r\n        this._widgets = new Map();\r\n    }\r\n    render(container, parameters) {\r\n        const id = this.counter;\r\n        this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));\r\n        this.counter++;\r\n        return id;\r\n    }\r\n    reset(optWidgetId) {\r\n        var _a;\r\n        const id = optWidgetId || _WIDGET_ID_START;\r\n        void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());\r\n        this._widgets.delete(id);\r\n    }\r\n    getResponse(optWidgetId) {\r\n        var _a;\r\n        const id = optWidgetId || _WIDGET_ID_START;\r\n        return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';\r\n    }\r\n    async execute(optWidgetId) {\r\n        var _a;\r\n        const id = optWidgetId || _WIDGET_ID_START;\r\n        void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());\r\n        return '';\r\n    }\r\n}\r\nclass MockWidget {\r\n    constructor(containerOrId, appName, params) {\r\n        this.params = params;\r\n        this.timerId = null;\r\n        this.deleted = false;\r\n        this.responseToken = null;\r\n        this.clickHandler = () => {\r\n            this.execute();\r\n        };\r\n        const container = typeof containerOrId === 'string'\r\n            ? document.getElementById(containerOrId)\r\n            : containerOrId;\r\n        _assert(container, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, { appName });\r\n        this.container = container;\r\n        this.isVisible = this.params.size !== 'invisible';\r\n        if (this.isVisible) {\r\n            this.execute();\r\n        }\r\n        else {\r\n            this.container.addEventListener('click', this.clickHandler);\r\n        }\r\n    }\r\n    getResponse() {\r\n        this.checkIfDeleted();\r\n        return this.responseToken;\r\n    }\r\n    delete() {\r\n        this.checkIfDeleted();\r\n        this.deleted = true;\r\n        if (this.timerId) {\r\n            clearTimeout(this.timerId);\r\n            this.timerId = null;\r\n        }\r\n        this.container.removeEventListener('click', this.clickHandler);\r\n    }\r\n    execute() {\r\n        this.checkIfDeleted();\r\n        if (this.timerId) {\r\n            return;\r\n        }\r\n        this.timerId = window.setTimeout(() => {\r\n            this.responseToken = generateRandomAlphaNumericString(50);\r\n            const { callback, 'expired-callback': expiredCallback } = this.params;\r\n            if (callback) {\r\n                try {\r\n                    callback(this.responseToken);\r\n                }\r\n                catch (e) { }\r\n            }\r\n            this.timerId = window.setTimeout(() => {\r\n                this.timerId = null;\r\n                this.responseToken = null;\r\n                if (expiredCallback) {\r\n                    try {\r\n                        expiredCallback();\r\n                    }\r\n                    catch (e) { }\r\n                }\r\n                if (this.isVisible) {\r\n                    this.execute();\r\n                }\r\n            }, _EXPIRATION_TIME_MS);\r\n        }, _SOLVE_TIME_MS);\r\n    }\r\n    checkIfDeleted() {\r\n        if (this.deleted) {\r\n            throw new Error('reCAPTCHA mock was already deleted!');\r\n        }\r\n    }\r\n}\r\nfunction generateRandomAlphaNumericString(len) {\r\n    const chars = [];\r\n    const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n    for (let i = 0; i < len; i++) {\r\n        chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));\r\n    }\r\n    return chars.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// ReCaptcha will load using the same callback, so the callback function needs\r\n// to be kept around\r\nconst _JSLOAD_CALLBACK = _generateCallbackName('rcb');\r\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\r\nconst RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';\r\n/**\r\n * Loader for the GReCaptcha library. There should only ever be one of this.\r\n */\r\nclass ReCaptchaLoaderImpl {\r\n    constructor() {\r\n        var _a;\r\n        this.hostLanguage = '';\r\n        this.counter = 0;\r\n        /**\r\n         * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\r\n         * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\r\n         * `window.grecaptcha.render()` will not. Another load will add it.\r\n         */\r\n        this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);\r\n    }\r\n    load(auth, hl = '') {\r\n        _assert(isHostLanguageValid(hl), auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\r\n            return Promise.resolve(_window().grecaptcha);\r\n        }\r\n        return new Promise((resolve, reject) => {\r\n            const networkTimeout = _window().setTimeout(() => {\r\n                reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n            }, NETWORK_TIMEOUT_DELAY.get());\r\n            _window()[_JSLOAD_CALLBACK] = () => {\r\n                _window().clearTimeout(networkTimeout);\r\n                delete _window()[_JSLOAD_CALLBACK];\r\n                const recaptcha = _window().grecaptcha;\r\n                if (!recaptcha || !isV2(recaptcha)) {\r\n                    reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n                    return;\r\n                }\r\n                // Wrap the greptcha render function so that we know if the developer has\r\n                // called it separately\r\n                const render = recaptcha.render;\r\n                recaptcha.render = (container, params) => {\r\n                    const widgetId = render(container, params);\r\n                    this.counter++;\r\n                    return widgetId;\r\n                };\r\n                this.hostLanguage = hl;\r\n                resolve(recaptcha);\r\n            };\r\n            const url = `${RECAPTCHA_BASE}?${querystring({\r\n                onload: _JSLOAD_CALLBACK,\r\n                render: 'explicit',\r\n                hl\r\n            })}`;\r\n            _loadJS(url).catch(() => {\r\n                clearTimeout(networkTimeout);\r\n                reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n            });\r\n        });\r\n    }\r\n    clearedOneInstance() {\r\n        this.counter--;\r\n    }\r\n    shouldResolveImmediately(hl) {\r\n        var _a;\r\n        // We can resolve immediately if:\r\n        //   • grecaptcha is already defined AND (\r\n        //     1. the requested language codes are the same OR\r\n        //     2. there exists already a ReCaptcha on the page\r\n        //     3. the library was already loaded by the app\r\n        // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\r\n        // that are already in the page\r\n        return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&\r\n            (hl === this.hostLanguage ||\r\n                this.counter > 0 ||\r\n                this.librarySeparatelyLoaded));\r\n    }\r\n}\r\nfunction isHostLanguageValid(hl) {\r\n    return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\r\n}\r\nclass MockReCaptchaLoaderImpl {\r\n    async load(auth) {\r\n        return new MockReCaptcha(auth);\r\n    }\r\n    clearedOneInstance() { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\r\nconst DEFAULT_PARAMS = {\r\n    theme: 'light',\r\n    type: 'image'\r\n};\r\n/**\r\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\r\n *\r\n * @remarks\r\n * `RecaptchaVerifier` does not work in a Node.js environment.\r\n *\r\n * @public\r\n */\r\nclass RecaptchaVerifier {\r\n    /**\r\n     * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n     *\r\n     * @param containerOrId - The reCAPTCHA container parameter.\r\n     *\r\n     * @remarks\r\n     * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\r\n     * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\r\n     * an element ID. The corresponding element must also must be in the DOM at the time of\r\n     * initialization.\r\n     *\r\n     * @param parameters - The optional reCAPTCHA parameters.\r\n     *\r\n     * @remarks\r\n     * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\r\n     * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\r\n     * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\r\n     * 'invisible'.\r\n     */\r\n    constructor(authExtern, containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS)) {\r\n        this.parameters = parameters;\r\n        /**\r\n         * The application verifier type.\r\n         *\r\n         * @remarks\r\n         * For a reCAPTCHA verifier, this is 'recaptcha'.\r\n         */\r\n        this.type = RECAPTCHA_VERIFIER_TYPE;\r\n        this.destroyed = false;\r\n        this.widgetId = null;\r\n        this.tokenChangeListeners = new Set();\r\n        this.renderPromise = null;\r\n        this.recaptcha = null;\r\n        this.auth = _castAuth(authExtern);\r\n        this.isInvisible = this.parameters.size === 'invisible';\r\n        _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n        const container = typeof containerOrId === 'string'\r\n            ? document.getElementById(containerOrId)\r\n            : containerOrId;\r\n        _assert(container, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        this.container = container;\r\n        this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\r\n        this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\r\n            ? new MockReCaptchaLoaderImpl()\r\n            : new ReCaptchaLoaderImpl();\r\n        this.validateStartingState();\r\n        // TODO: Figure out if sdk version is needed\r\n    }\r\n    /**\r\n     * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\r\n     *\r\n     * @returns A Promise for the reCAPTCHA token.\r\n     */\r\n    async verify() {\r\n        this.assertNotDestroyed();\r\n        const id = await this.render();\r\n        const recaptcha = this.getAssertedRecaptcha();\r\n        const response = recaptcha.getResponse(id);\r\n        if (response) {\r\n            return response;\r\n        }\r\n        return new Promise(resolve => {\r\n            const tokenChange = (token) => {\r\n                if (!token) {\r\n                    return; // Ignore token expirations.\r\n                }\r\n                this.tokenChangeListeners.delete(tokenChange);\r\n                resolve(token);\r\n            };\r\n            this.tokenChangeListeners.add(tokenChange);\r\n            if (this.isInvisible) {\r\n                recaptcha.execute(id);\r\n            }\r\n        });\r\n    }\r\n    /**\r\n     * Renders the reCAPTCHA widget on the page.\r\n     *\r\n     * @returns A Promise that resolves with the reCAPTCHA widget ID.\r\n     */\r\n    render() {\r\n        try {\r\n            this.assertNotDestroyed();\r\n        }\r\n        catch (e) {\r\n            // This method returns a promise. Since it's not async (we want to return the\r\n            // _same_ promise if rendering is still occurring), the API surface should\r\n            // reject with the error rather than just throw\r\n            return Promise.reject(e);\r\n        }\r\n        if (this.renderPromise) {\r\n            return this.renderPromise;\r\n        }\r\n        this.renderPromise = this.makeRenderPromise().catch(e => {\r\n            this.renderPromise = null;\r\n            throw e;\r\n        });\r\n        return this.renderPromise;\r\n    }\r\n    /** @internal */\r\n    _reset() {\r\n        this.assertNotDestroyed();\r\n        if (this.widgetId !== null) {\r\n            this.getAssertedRecaptcha().reset(this.widgetId);\r\n        }\r\n    }\r\n    /**\r\n     * Clears the reCAPTCHA widget from the page and destroys the instance.\r\n     */\r\n    clear() {\r\n        this.assertNotDestroyed();\r\n        this.destroyed = true;\r\n        this._recaptchaLoader.clearedOneInstance();\r\n        if (!this.isInvisible) {\r\n            this.container.childNodes.forEach(node => {\r\n                this.container.removeChild(node);\r\n            });\r\n        }\r\n    }\r\n    validateStartingState() {\r\n        _assert(!this.parameters.sitekey, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n    }\r\n    makeTokenCallback(existing) {\r\n        return token => {\r\n            this.tokenChangeListeners.forEach(listener => listener(token));\r\n            if (typeof existing === 'function') {\r\n                existing(token);\r\n            }\r\n            else if (typeof existing === 'string') {\r\n                const globalFunc = _window()[existing];\r\n                if (typeof globalFunc === 'function') {\r\n                    globalFunc(token);\r\n                }\r\n            }\r\n        };\r\n    }\r\n    assertNotDestroyed() {\r\n        _assert(!this.destroyed, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    }\r\n    async makeRenderPromise() {\r\n        await this.init();\r\n        if (!this.widgetId) {\r\n            let container = this.container;\r\n            if (!this.isInvisible) {\r\n                const guaranteedEmpty = document.createElement('div');\r\n                container.appendChild(guaranteedEmpty);\r\n                container = guaranteedEmpty;\r\n            }\r\n            this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);\r\n        }\r\n        return this.widgetId;\r\n    }\r\n    async init() {\r\n        _assert(_isHttpOrHttps() && !_isWorker(), this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        await domReady();\r\n        this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);\r\n        const siteKey = await getRecaptchaParams(this.auth);\r\n        _assert(siteKey, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        this.parameters.sitekey = siteKey;\r\n    }\r\n    getAssertedRecaptcha() {\r\n        _assert(this.recaptcha, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        return this.recaptcha;\r\n    }\r\n}\r\nfunction domReady() {\r\n    let resolver = null;\r\n    return new Promise(resolve => {\r\n        if (document.readyState === 'complete') {\r\n            resolve();\r\n            return;\r\n        }\r\n        // Document not ready, wait for load before resolving.\r\n        // Save resolver, so we can remove listener in case it was externally\r\n        // cancelled.\r\n        resolver = () => resolve();\r\n        window.addEventListener('load', resolver);\r\n    }).catch(e => {\r\n        if (resolver) {\r\n            window.removeEventListener('load', resolver);\r\n        }\r\n        throw e;\r\n    });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ConfirmationResultImpl {\r\n    constructor(verificationId, onConfirmation) {\r\n        this.verificationId = verificationId;\r\n        this.onConfirmation = onConfirmation;\r\n    }\r\n    confirm(verificationCode) {\r\n        const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);\r\n        return this.onConfirmation(authCredential);\r\n    }\r\n}\r\n/**\r\n * Asynchronously signs in using a phone number.\r\n *\r\n * @remarks\r\n * This method sends a code via SMS to the given\r\n * phone number, and returns a {@link ConfirmationResult}. After the user\r\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\r\n * with the code to sign the user in.\r\n *\r\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\r\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\r\n * This function can work on other platforms that do not support the\r\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\r\n * third-party {@link ApplicationVerifier} implementation.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain a verificationCode from the user.\r\n * const credential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {\r\n    const authInternal = _castAuth(auth);\r\n    const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));\r\n    return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));\r\n}\r\n/**\r\n * Links the user account with the given phone number.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n    const userInternal = getModularInstance(user);\r\n    await _assertLinkedStatus(false, userInternal, \"phone\" /* ProviderId.PHONE */);\r\n    const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n    return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh phone credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n    const userInternal = getModularInstance(user);\r\n    const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n    return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\r\n *\r\n */\r\nasync function _verifyPhoneNumber(auth, options, verifier) {\r\n    var _a;\r\n    const recaptchaToken = await verifier.verify();\r\n    try {\r\n        _assert(typeof recaptchaToken === 'string', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        let phoneInfoOptions;\r\n        if (typeof options === 'string') {\r\n            phoneInfoOptions = {\r\n                phoneNumber: options\r\n            };\r\n        }\r\n        else {\r\n            phoneInfoOptions = options;\r\n        }\r\n        if ('session' in phoneInfoOptions) {\r\n            const session = phoneInfoOptions.session;\r\n            if ('phoneNumber' in phoneInfoOptions) {\r\n                _assert(session.type === \"enroll\" /* MultiFactorSessionType.ENROLL */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n                const response = await startEnrollPhoneMfa(auth, {\r\n                    idToken: session.credential,\r\n                    phoneEnrollmentInfo: {\r\n                        phoneNumber: phoneInfoOptions.phoneNumber,\r\n                        recaptchaToken\r\n                    }\r\n                });\r\n                return response.phoneSessionInfo.sessionInfo;\r\n            }\r\n            else {\r\n                _assert(session.type === \"signin\" /* MultiFactorSessionType.SIGN_IN */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n                const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||\r\n                    phoneInfoOptions.multiFactorUid;\r\n                _assert(mfaEnrollmentId, auth, \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */);\r\n                const response = await startSignInPhoneMfa(auth, {\r\n                    mfaPendingCredential: session.credential,\r\n                    mfaEnrollmentId,\r\n                    phoneSignInInfo: {\r\n                        recaptchaToken\r\n                    }\r\n                });\r\n                return response.phoneResponseInfo.sessionInfo;\r\n            }\r\n        }\r\n        else {\r\n            const { sessionInfo } = await sendPhoneVerificationCode(auth, {\r\n                phoneNumber: phoneInfoOptions.phoneNumber,\r\n                recaptchaToken\r\n            });\r\n            return sessionInfo;\r\n        }\r\n    }\r\n    finally {\r\n        verifier._reset();\r\n    }\r\n}\r\n/**\r\n * Updates the user's phone number.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * await updatePhoneNumber(user, phoneCredential);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param credential - A credential authenticating the new phone number.\r\n *\r\n * @public\r\n */\r\nasync function updatePhoneNumber(user, credential) {\r\n    await _link$1(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link PhoneAuthCredential}.\r\n *\r\n * @remarks\r\n * `PhoneAuthProvider` does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, phoneCredential);\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthProvider {\r\n    /**\r\n     * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\r\n     *\r\n     */\r\n    constructor(auth) {\r\n        /** Always set to {@link ProviderId}.PHONE. */\r\n        this.providerId = PhoneAuthProvider.PROVIDER_ID;\r\n        this.auth = _castAuth(auth);\r\n    }\r\n    /**\r\n     *\r\n     * Starts a phone number authentication flow by sending a verification code to the given phone\r\n     * number.\r\n     *\r\n     * @example\r\n     * ```javascript\r\n     * const provider = new PhoneAuthProvider(auth);\r\n     * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n     * // Obtain verificationCode from the user.\r\n     * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n     * const userCredential = await signInWithCredential(auth, authCredential);\r\n     * ```\r\n     *\r\n     * @example\r\n     * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n     * ```javascript\r\n     * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n     * // Obtain verificationCode from the user.\r\n     * const userCredential = confirmationResult.confirm(verificationCode);\r\n     * ```\r\n     *\r\n     * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\r\n     * E.164 format (e.g. +16505550101).\r\n     * @param applicationVerifier - For abuse prevention, this method also requires a\r\n     * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\r\n     * {@link RecaptchaVerifier}.\r\n     *\r\n     * @returns A Promise for a verification ID that can be passed to\r\n     * {@link PhoneAuthProvider.credential} to identify this flow..\r\n     */\r\n    verifyPhoneNumber(phoneOptions, applicationVerifier) {\r\n        return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));\r\n    }\r\n    /**\r\n     * Creates a phone auth credential, given the verification ID from\r\n     * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\r\n     * mobile device.\r\n     *\r\n     * @example\r\n     * ```javascript\r\n     * const provider = new PhoneAuthProvider(auth);\r\n     * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n     * // Obtain verificationCode from the user.\r\n     * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n     * const userCredential = signInWithCredential(auth, authCredential);\r\n     * ```\r\n     *\r\n     * @example\r\n     * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n     * ```javascript\r\n     * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n     * // Obtain verificationCode from the user.\r\n     * const userCredential = await confirmationResult.confirm(verificationCode);\r\n     * ```\r\n     *\r\n     * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\r\n     * @param verificationCode - The verification code sent to the user's mobile device.\r\n     *\r\n     * @returns The auth provider credential.\r\n     */\r\n    static credential(verificationId, verificationCode) {\r\n        return PhoneAuthCredential._fromVerification(verificationId, verificationCode);\r\n    }\r\n    /**\r\n     * Generates an {@link AuthCredential} from a {@link UserCredential}.\r\n     * @param userCredential - The user credential.\r\n     */\r\n    static credentialFromResult(userCredential) {\r\n        const credential = userCredential;\r\n        return PhoneAuthProvider.credentialFromTaggedObject(credential);\r\n    }\r\n    /**\r\n     * Returns an {@link AuthCredential} when passed an error.\r\n     *\r\n     * @remarks\r\n     *\r\n     * This method works for errors like\r\n     * `auth/account-exists-with-different-credentials`. This is useful for\r\n     * recovering when attempting to set a user's phone number but the number\r\n     * in question is already tied to another account. For example, the following\r\n     * code tries to update the current user's phone number, and if that\r\n     * fails, links the user with the account associated with that number:\r\n     *\r\n     * ```js\r\n     * const provider = new PhoneAuthProvider(auth);\r\n     * const verificationId = await provider.verifyPhoneNumber(number, verifier);\r\n     * try {\r\n     *   const code = ''; // Prompt the user for the verification code\r\n     *   await updatePhoneNumber(\r\n     *       auth.currentUser,\r\n     *       PhoneAuthProvider.credential(verificationId, code));\r\n     * } catch (e) {\r\n     *   if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\r\n     *     const cred = PhoneAuthProvider.credentialFromError(e);\r\n     *     await linkWithCredential(auth.currentUser, cred);\r\n     *   }\r\n     * }\r\n     *\r\n     * // At this point, auth.currentUser.phoneNumber === number.\r\n     * ```\r\n     *\r\n     * @param error - The error to generate a credential from.\r\n     */\r\n    static credentialFromError(error) {\r\n        return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n    }\r\n    static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n        if (!tokenResponse) {\r\n            return null;\r\n        }\r\n        const { phoneNumber, temporaryProof } = tokenResponse;\r\n        if (phoneNumber && temporaryProof) {\r\n            return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);\r\n        }\r\n        return null;\r\n    }\r\n}\r\n/** Always set to {@link ProviderId}.PHONE. */\r\nPhoneAuthProvider.PROVIDER_ID = \"phone\" /* ProviderId.PHONE */;\r\n/** Always set to {@link SignInMethod}.PHONE. */\r\nPhoneAuthProvider.PHONE_SIGN_IN_METHOD = \"phone\" /* SignInMethod.PHONE */;\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Chooses a popup/redirect resolver to use. This prefers the override (which\r\n * is directly passed in), and falls back to the property set on the auth\r\n * object. If neither are available, this function errors w/ an argument error.\r\n */\r\nfunction _withDefaultResolver(auth, resolverOverride) {\r\n    if (resolverOverride) {\r\n        return _getInstance(resolverOverride);\r\n    }\r\n    _assert(auth._popupRedirectResolver, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n    return auth._popupRedirectResolver;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass IdpCredential extends AuthCredential {\r\n    constructor(params) {\r\n        super(\"custom\" /* ProviderId.CUSTOM */, \"custom\" /* ProviderId.CUSTOM */);\r\n        this.params = params;\r\n    }\r\n    _getIdTokenResponse(auth) {\r\n        return signInWithIdp(auth, this._buildIdpRequest());\r\n    }\r\n    _linkToIdToken(auth, idToken) {\r\n        return signInWithIdp(auth, this._buildIdpRequest(idToken));\r\n    }\r\n    _getReauthenticationResolver(auth) {\r\n        return signInWithIdp(auth, this._buildIdpRequest());\r\n    }\r\n    _buildIdpRequest(idToken) {\r\n        const request = {\r\n            requestUri: this.params.requestUri,\r\n            sessionId: this.params.sessionId,\r\n            postBody: this.params.postBody,\r\n            tenantId: this.params.tenantId,\r\n            pendingToken: this.params.pendingToken,\r\n            returnSecureToken: true,\r\n            returnIdpCredential: true\r\n        };\r\n        if (idToken) {\r\n            request.idToken = idToken;\r\n        }\r\n        return request;\r\n    }\r\n}\r\nfunction _signIn(params) {\r\n    return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nfunction _reauth(params) {\r\n    const { auth, user } = params;\r\n    _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nasync function _link(params) {\r\n    const { auth, user } = params;\r\n    _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    return _link$1(user, new IdpCredential(params), params.bypassAuthState);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n */\r\nclass AbstractPopupRedirectOperation {\r\n    constructor(auth, filter, resolver, user, bypassAuthState = false) {\r\n        this.auth = auth;\r\n        this.resolver = resolver;\r\n        this.user = user;\r\n        this.bypassAuthState = bypassAuthState;\r\n        this.pendingPromise = null;\r\n        this.eventManager = null;\r\n        this.filter = Array.isArray(filter) ? filter : [filter];\r\n    }\r\n    execute() {\r\n        return new Promise(async (resolve, reject) => {\r\n            this.pendingPromise = { resolve, reject };\r\n            try {\r\n                this.eventManager = await this.resolver._initialize(this.auth);\r\n                await this.onExecution();\r\n                this.eventManager.registerConsumer(this);\r\n            }\r\n            catch (e) {\r\n                this.reject(e);\r\n            }\r\n        });\r\n    }\r\n    async onAuthEvent(event) {\r\n        const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\r\n        if (error) {\r\n            this.reject(error);\r\n            return;\r\n        }\r\n        const params = {\r\n            auth: this.auth,\r\n            requestUri: urlResponse,\r\n            sessionId: sessionId,\r\n            tenantId: tenantId || undefined,\r\n            postBody: postBody || undefined,\r\n            user: this.user,\r\n            bypassAuthState: this.bypassAuthState\r\n        };\r\n        try {\r\n            this.resolve(await this.getIdpTask(type)(params));\r\n        }\r\n        catch (e) {\r\n            this.reject(e);\r\n        }\r\n    }\r\n    onError(error) {\r\n        this.reject(error);\r\n    }\r\n    getIdpTask(type) {\r\n        switch (type) {\r\n            case \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */:\r\n            case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n                return _signIn;\r\n            case \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */:\r\n            case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n                return _link;\r\n            case \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */:\r\n            case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n                return _reauth;\r\n            default:\r\n                _fail(this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        }\r\n    }\r\n    resolve(cred) {\r\n        debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n        this.pendingPromise.resolve(cred);\r\n        this.unregisterAndCleanUp();\r\n    }\r\n    reject(error) {\r\n        debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n        this.pendingPromise.reject(error);\r\n        this.unregisterAndCleanUp();\r\n    }\r\n    unregisterAndCleanUp() {\r\n        if (this.eventManager) {\r\n            this.eventManager.unregisterConsumer(this);\r\n        }\r\n        this.pendingPromise = null;\r\n        this.cleanUp();\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\r\n/**\r\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\r\n *\r\n * @remarks\r\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\r\n * unsuccessful, returns an error object containing additional information about the error.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPopup(auth, provider, resolver) {\r\n    const authInternal = _castAuth(auth);\r\n    _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n    const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n    const action = new PopupOperation(authInternal, \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);\r\n    return action.executeNotNull();\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\r\n * OAuth flow.\r\n *\r\n * @remarks\r\n * If the reauthentication is successful, the returned result will contain the user and the\r\n * provider's credential.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n * // Reauthenticate using a popup.\r\n * await reauthenticateWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPopup(user, provider, resolver) {\r\n    const userInternal = getModularInstance(user);\r\n    _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n    const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n    const action = new PopupOperation(userInternal.auth, \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n    return action.executeNotNull();\r\n}\r\n/**\r\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\r\n *\r\n * @remarks\r\n * If the linking is successful, the returned result will contain the user and the provider's credential.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPopup(user, provider, resolver) {\r\n    const userInternal = getModularInstance(user);\r\n    _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n    const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n    const action = new PopupOperation(userInternal.auth, \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n    return action.executeNotNull();\r\n}\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n *\r\n */\r\nclass PopupOperation extends AbstractPopupRedirectOperation {\r\n    constructor(auth, filter, provider, resolver, user) {\r\n        super(auth, filter, resolver, user);\r\n        this.provider = provider;\r\n        this.authWindow = null;\r\n        this.pollId = null;\r\n        if (PopupOperation.currentPopupAction) {\r\n            PopupOperation.currentPopupAction.cancel();\r\n        }\r\n        PopupOperation.currentPopupAction = this;\r\n    }\r\n    async executeNotNull() {\r\n        const result = await this.execute();\r\n        _assert(result, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        return result;\r\n    }\r\n    async onExecution() {\r\n        debugAssert(this.filter.length === 1, 'Popup operations only handle one event');\r\n        const eventId = _generateEventId();\r\n        this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor\r\n        eventId);\r\n        this.authWindow.associatedEvent = eventId;\r\n        // Check for web storage support and origin validation _after_ the popup is\r\n        // loaded. These operations are slow (~1 second or so) Rather than\r\n        // waiting on them before opening the window, optimistically open the popup\r\n        // and check for storage support at the same time. If storage support is\r\n        // not available, this will cause the whole thing to reject properly. It\r\n        // will also close the popup, but since the promise has already rejected,\r\n        // the popup closed by user poll will reject into the void.\r\n        this.resolver._originValidation(this.auth).catch(e => {\r\n            this.reject(e);\r\n        });\r\n        this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\r\n            if (!isSupported) {\r\n                this.reject(_createError(this.auth, \"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));\r\n            }\r\n        });\r\n        // Handle user closure. Notice this does *not* use await\r\n        this.pollUserCancellation();\r\n    }\r\n    get eventId() {\r\n        var _a;\r\n        return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;\r\n    }\r\n    cancel() {\r\n        this.reject(_createError(this.auth, \"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));\r\n    }\r\n    cleanUp() {\r\n        if (this.authWindow) {\r\n            this.authWindow.close();\r\n        }\r\n        if (this.pollId) {\r\n            window.clearTimeout(this.pollId);\r\n        }\r\n        this.authWindow = null;\r\n        this.pollId = null;\r\n        PopupOperation.currentPopupAction = null;\r\n    }\r\n    pollUserCancellation() {\r\n        const poll = () => {\r\n            var _a, _b;\r\n            if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {\r\n                // Make sure that there is sufficient time for whatever action to\r\n                // complete. The window could have closed but the sign in network\r\n                // call could still be in flight. This is specifically true for\r\n                // Firefox or if the opener is in an iframe, in which case the oauth\r\n                // helper closes the popup.\r\n                this.pollId = window.setTimeout(() => {\r\n                    this.pollId = null;\r\n                    this.reject(_createError(this.auth, \"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));\r\n                }, 8000 /* _Timeout.AUTH_EVENT */);\r\n                return;\r\n            }\r\n            this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\r\n        };\r\n        poll();\r\n    }\r\n}\r\n// Only one popup is ever shown at once. The lifecycle of the current popup\r\n// can be managed / cancelled by the constructor.\r\nPopupOperation.currentPopupAction = null;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\r\n// We only get one redirect outcome for any one auth, so just store it\r\n// in here.\r\nconst redirectOutcomeMap = new Map();\r\nclass RedirectAction extends AbstractPopupRedirectOperation {\r\n    constructor(auth, resolver, bypassAuthState = false) {\r\n        super(auth, [\r\n            \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,\r\n            \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */,\r\n            \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */,\r\n            \"unknown\" /* AuthEventType.UNKNOWN */\r\n        ], resolver, undefined, bypassAuthState);\r\n        this.eventId = null;\r\n    }\r\n    /**\r\n     * Override the execute function; if we already have a redirect result, then\r\n     * just return it.\r\n     */\r\n    async execute() {\r\n        let readyOutcome = redirectOutcomeMap.get(this.auth._key());\r\n        if (!readyOutcome) {\r\n            try {\r\n                const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);\r\n                const result = hasPendingRedirect ? await super.execute() : null;\r\n                readyOutcome = () => Promise.resolve(result);\r\n            }\r\n            catch (e) {\r\n                readyOutcome = () => Promise.reject(e);\r\n            }\r\n            redirectOutcomeMap.set(this.auth._key(), readyOutcome);\r\n        }\r\n        // If we're not bypassing auth state, the ready outcome should be set to\r\n        // null.\r\n        if (!this.bypassAuthState) {\r\n            redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\r\n        }\r\n        return readyOutcome();\r\n    }\r\n    async onAuthEvent(event) {\r\n        if (event.type === \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {\r\n            return super.onAuthEvent(event);\r\n        }\r\n        else if (event.type === \"unknown\" /* AuthEventType.UNKNOWN */) {\r\n            // This is a sentinel value indicating there's no pending redirect\r\n            this.resolve(null);\r\n            return;\r\n        }\r\n        if (event.eventId) {\r\n            const user = await this.auth._redirectUserForId(event.eventId);\r\n            if (user) {\r\n                this.user = user;\r\n                return super.onAuthEvent(event);\r\n            }\r\n            else {\r\n                this.resolve(null);\r\n            }\r\n        }\r\n    }\r\n    async onExecution() { }\r\n    cleanUp() { }\r\n}\r\nasync function _getAndClearPendingRedirectStatus(resolver, auth) {\r\n    const key = pendingRedirectKey(auth);\r\n    const persistence = resolverPersistence(resolver);\r\n    if (!(await persistence._isAvailable())) {\r\n        return false;\r\n    }\r\n    const hasPendingRedirect = (await persistence._get(key)) === 'true';\r\n    await persistence._remove(key);\r\n    return hasPendingRedirect;\r\n}\r\nasync function _setPendingRedirectStatus(resolver, auth) {\r\n    return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\r\n}\r\nfunction _clearRedirectOutcomes() {\r\n    redirectOutcomeMap.clear();\r\n}\r\nfunction _overrideRedirectResult(auth, result) {\r\n    redirectOutcomeMap.set(auth._key(), result);\r\n}\r\nfunction resolverPersistence(resolver) {\r\n    return _getInstance(resolver._redirectPersistence);\r\n}\r\nfunction pendingRedirectKey(auth) {\r\n    return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Authenticates a Firebase client using a full-page redirect flow.\r\n *\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link signInWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n *   // This is the signed-in user\r\n *   const user = result.user;\r\n *   // This gives you a Facebook Access Token.\r\n *   const credential = provider.credentialFromResult(auth, result);\r\n *   const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction signInWithRedirect(auth, provider, resolver) {\r\n    return _signInWithRedirect(auth, provider, resolver);\r\n}\r\nasync function _signInWithRedirect(auth, provider, resolver) {\r\n    const authInternal = _castAuth(auth);\r\n    _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n    // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n    // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n    // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n    await authInternal._initializationPromise;\r\n    const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n    await _setPendingRedirectStatus(resolverInternal, authInternal);\r\n    return resolverInternal._openRedirect(authInternal, provider, \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */);\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link reauthenticateWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * // Reauthenticate using a redirect.\r\n * await reauthenticateWithRedirect(result.user, provider);\r\n * // This will again trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction reauthenticateWithRedirect(user, provider, resolver) {\r\n    return _reauthenticateWithRedirect(user, provider, resolver);\r\n}\r\nasync function _reauthenticateWithRedirect(user, provider, resolver) {\r\n    const userInternal = getModularInstance(user);\r\n    _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n    // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n    // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n    // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n    await userInternal.auth._initializationPromise;\r\n    // Allow the resolver to error before persisting the redirect user\r\n    const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n    await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n    const eventId = await prepareUserForRedirect(userInternal);\r\n    return resolverInternal._openRedirect(userInternal.auth, provider, \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link linkWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithRedirect(result.user, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction linkWithRedirect(user, provider, resolver) {\r\n    return _linkWithRedirect(user, provider, resolver);\r\n}\r\nasync function _linkWithRedirect(user, provider, resolver) {\r\n    const userInternal = getModularInstance(user);\r\n    _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n    // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n    // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n    // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n    await userInternal.auth._initializationPromise;\r\n    // Allow the resolver to error before persisting the redirect user\r\n    const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n    await _assertLinkedStatus(false, userInternal, provider.providerId);\r\n    await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n    const eventId = await prepareUserForRedirect(userInternal);\r\n    return resolverInternal._openRedirect(userInternal.auth, provider, \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\r\n *\r\n * @remarks\r\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\r\n * error. If no redirect operation was called, returns `null`.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n *   // This is the signed-in user\r\n *   const user = result.user;\r\n *   // This gives you a Facebook Access Token.\r\n *   const credential = provider.credentialFromResult(auth, result);\r\n *   const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function getRedirectResult(auth, resolver) {\r\n    await _castAuth(auth)._initializationPromise;\r\n    return _getRedirectResult(auth, resolver, false);\r\n}\r\nasync function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {\r\n    const authInternal = _castAuth(auth);\r\n    const resolver = _withDefaultResolver(authInternal, resolverExtern);\r\n    const action = new RedirectAction(authInternal, resolver, bypassAuthState);\r\n    const result = await action.execute();\r\n    if (result && !bypassAuthState) {\r\n        delete result.user._redirectEventId;\r\n        await authInternal._persistUserIfCurrent(result.user);\r\n        await authInternal._setRedirectUser(null, resolverExtern);\r\n    }\r\n    return result;\r\n}\r\nasync function prepareUserForRedirect(user) {\r\n    const eventId = _generateEventId(`${user.uid}:::`);\r\n    user._redirectEventId = eventId;\r\n    await user.auth._setRedirectUser(user);\r\n    await user.auth._persistUserIfCurrent(user);\r\n    return eventId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// The amount of time to store the UIDs of seen events; this is\r\n// set to 10 min by default\r\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\r\nclass AuthEventManager {\r\n    constructor(auth) {\r\n        this.auth = auth;\r\n        this.cachedEventUids = new Set();\r\n        this.consumers = new Set();\r\n        this.queuedRedirectEvent = null;\r\n        this.hasHandledPotentialRedirect = false;\r\n        this.lastProcessedEventTime = Date.now();\r\n    }\r\n    registerConsumer(authEventConsumer) {\r\n        this.consumers.add(authEventConsumer);\r\n        if (this.queuedRedirectEvent &&\r\n            this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {\r\n            this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\r\n            this.saveEventToCache(this.queuedRedirectEvent);\r\n            this.queuedRedirectEvent = null;\r\n        }\r\n    }\r\n    unregisterConsumer(authEventConsumer) {\r\n        this.consumers.delete(authEventConsumer);\r\n    }\r\n    onEvent(event) {\r\n        // Check if the event has already been handled\r\n        if (this.hasEventBeenHandled(event)) {\r\n            return false;\r\n        }\r\n        let handled = false;\r\n        this.consumers.forEach(consumer => {\r\n            if (this.isEventForConsumer(event, consumer)) {\r\n                handled = true;\r\n                this.sendToConsumer(event, consumer);\r\n                this.saveEventToCache(event);\r\n            }\r\n        });\r\n        if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\r\n            // If we've already seen a redirect before, or this is a popup event,\r\n            // bail now\r\n            return handled;\r\n        }\r\n        this.hasHandledPotentialRedirect = true;\r\n        // If the redirect wasn't handled, hang on to it\r\n        if (!handled) {\r\n            this.queuedRedirectEvent = event;\r\n            handled = true;\r\n        }\r\n        return handled;\r\n    }\r\n    sendToConsumer(event, consumer) {\r\n        var _a;\r\n        if (event.error && !isNullRedirectEvent(event)) {\r\n            const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||\r\n                \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */;\r\n            consumer.onError(_createError(this.auth, code));\r\n        }\r\n        else {\r\n            consumer.onAuthEvent(event);\r\n        }\r\n    }\r\n    isEventForConsumer(event, consumer) {\r\n        const eventIdMatches = consumer.eventId === null ||\r\n            (!!event.eventId && event.eventId === consumer.eventId);\r\n        return consumer.filter.includes(event.type) && eventIdMatches;\r\n    }\r\n    hasEventBeenHandled(event) {\r\n        if (Date.now() - this.lastProcessedEventTime >=\r\n            EVENT_DUPLICATION_CACHE_DURATION_MS) {\r\n            this.cachedEventUids.clear();\r\n        }\r\n        return this.cachedEventUids.has(eventUid(event));\r\n    }\r\n    saveEventToCache(event) {\r\n        this.cachedEventUids.add(eventUid(event));\r\n        this.lastProcessedEventTime = Date.now();\r\n    }\r\n}\r\nfunction eventUid(e) {\r\n    return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\r\n}\r\nfunction isNullRedirectEvent({ type, error }) {\r\n    return (type === \"unknown\" /* AuthEventType.UNKNOWN */ &&\r\n        (error === null || error === void 0 ? void 0 : error.code) === `auth/${\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */}`);\r\n}\r\nfunction isRedirectEvent(event) {\r\n    switch (event.type) {\r\n        case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n        case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n        case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n            return true;\r\n        case \"unknown\" /* AuthEventType.UNKNOWN */:\r\n            return isNullRedirectEvent(event);\r\n        default:\r\n            return false;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _getProjectConfig(auth, request = {}) {\r\n    return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/projects\" /* Endpoint.GET_PROJECT_CONFIG */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\r\nconst HTTP_REGEX = /^https?/;\r\nasync function _validateOrigin(auth) {\r\n    // Skip origin validation if we are in an emulated environment\r\n    if (auth.config.emulator) {\r\n        return;\r\n    }\r\n    const { authorizedDomains } = await _getProjectConfig(auth);\r\n    for (const domain of authorizedDomains) {\r\n        try {\r\n            if (matchDomain(domain)) {\r\n                return;\r\n            }\r\n        }\r\n        catch (_a) {\r\n            // Do nothing if there's a URL error; just continue searching\r\n        }\r\n    }\r\n    // In the old SDK, this error also provides helpful messages.\r\n    _fail(auth, \"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */);\r\n}\r\nfunction matchDomain(expected) {\r\n    const currentUrl = _getCurrentUrl();\r\n    const { protocol, hostname } = new URL(currentUrl);\r\n    if (expected.startsWith('chrome-extension://')) {\r\n        const ceUrl = new URL(expected);\r\n        if (ceUrl.hostname === '' && hostname === '') {\r\n            // For some reason we're not parsing chrome URLs properly\r\n            return (protocol === 'chrome-extension:' &&\r\n                expected.replace('chrome-extension://', '') ===\r\n                    currentUrl.replace('chrome-extension://', ''));\r\n        }\r\n        return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\r\n    }\r\n    if (!HTTP_REGEX.test(protocol)) {\r\n        return false;\r\n    }\r\n    if (IP_ADDRESS_REGEX.test(expected)) {\r\n        // The domain has to be exactly equal to the pattern, as an IP domain will\r\n        // only contain the IP, no extra character.\r\n        return hostname === expected;\r\n    }\r\n    // Dots in pattern should be escaped.\r\n    const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\r\n    // Non ip address domains.\r\n    // domain.com = *.domain.com OR domain.com\r\n    const re = new RegExp('^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');\r\n    return re.test(hostname);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\r\n/**\r\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\r\n * it will stop working after a retrial. This is a hack to fix this issue.\r\n */\r\nfunction resetUnloadedGapiModules() {\r\n    // Clear last failed gapi.load state to force next gapi.load to first\r\n    // load the failed gapi.iframes module.\r\n    // Get gapix.beacon context.\r\n    const beacon = _window().___jsl;\r\n    // Get current hint.\r\n    if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {\r\n        // Get gapi hint.\r\n        for (const hint of Object.keys(beacon.H)) {\r\n            // Requested modules.\r\n            beacon.H[hint].r = beacon.H[hint].r || [];\r\n            // Loaded modules.\r\n            beacon.H[hint].L = beacon.H[hint].L || [];\r\n            // Set requested modules to a copy of the loaded modules.\r\n            beacon.H[hint].r = [...beacon.H[hint].L];\r\n            // Clear pending callbacks.\r\n            if (beacon.CP) {\r\n                for (let i = 0; i < beacon.CP.length; i++) {\r\n                    // Remove all failed pending callbacks.\r\n                    beacon.CP[i] = null;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\nfunction loadGapi(auth) {\r\n    return new Promise((resolve, reject) => {\r\n        var _a, _b, _c;\r\n        // Function to run when gapi.load is ready.\r\n        function loadGapiIframe() {\r\n            // The developer may have tried to previously run gapi.load and failed.\r\n            // Run this to fix that.\r\n            resetUnloadedGapiModules();\r\n            gapi.load('gapi.iframes', {\r\n                callback: () => {\r\n                    resolve(gapi.iframes.getContext());\r\n                },\r\n                ontimeout: () => {\r\n                    // The above reset may be sufficient, but having this reset after\r\n                    // failure ensures that if the developer calls gapi.load after the\r\n                    // connection is re-established and before another attempt to embed\r\n                    // the iframe, it would work and would not be broken because of our\r\n                    // failed attempt.\r\n                    // Timeout when gapi.iframes.Iframe not loaded.\r\n                    resetUnloadedGapiModules();\r\n                    reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n                },\r\n                timeout: NETWORK_TIMEOUT.get()\r\n            });\r\n        }\r\n        if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {\r\n            // If gapi.iframes.Iframe available, resolve.\r\n            resolve(gapi.iframes.getContext());\r\n        }\r\n        else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {\r\n            // Gapi loader ready, load gapi.iframes.\r\n            loadGapiIframe();\r\n        }\r\n        else {\r\n            // Create a new iframe callback when this is called so as not to overwrite\r\n            // any previous defined callback. This happens if this method is called\r\n            // multiple times in parallel and could result in the later callback\r\n            // overwriting the previous one. This would end up with a iframe\r\n            // timeout.\r\n            const cbName = _generateCallbackName('iframefcb');\r\n            // GApi loader not available, dynamically load platform.js.\r\n            _window()[cbName] = () => {\r\n                // GApi loader should be ready.\r\n                if (!!gapi.load) {\r\n                    loadGapiIframe();\r\n                }\r\n                else {\r\n                    // Gapi loader failed, throw error.\r\n                    reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n                }\r\n            };\r\n            // Load GApi loader.\r\n            return _loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`)\r\n                .catch(e => reject(e));\r\n        }\r\n    }).catch(error => {\r\n        // Reset cached promise to allow for retrial.\r\n        cachedGApiLoader = null;\r\n        throw error;\r\n    });\r\n}\r\nlet cachedGApiLoader = null;\r\nfunction _loadGapi(auth) {\r\n    cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\r\n    return cachedGApiLoader;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PING_TIMEOUT = new Delay(5000, 15000);\r\nconst IFRAME_PATH = '__/auth/iframe';\r\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\r\nconst IFRAME_ATTRIBUTES = {\r\n    style: {\r\n        position: 'absolute',\r\n        top: '-100px',\r\n        width: '1px',\r\n        height: '1px'\r\n    },\r\n    'aria-hidden': 'true',\r\n    tabindex: '-1'\r\n};\r\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\r\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\r\nconst EID_FROM_APIHOST = new Map([\r\n    [\"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */, 'p'],\r\n    ['staging-identitytoolkit.sandbox.googleapis.com', 's'],\r\n    ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\r\n]);\r\nfunction getIframeUrl(auth) {\r\n    const config = auth.config;\r\n    _assert(config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n    const url = config.emulator\r\n        ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\r\n        : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\r\n    const params = {\r\n        apiKey: config.apiKey,\r\n        appName: auth.name,\r\n        v: SDK_VERSION\r\n    };\r\n    const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\r\n    if (eid) {\r\n        params.eid = eid;\r\n    }\r\n    const frameworks = auth._getFrameworks();\r\n    if (frameworks.length) {\r\n        params.fw = frameworks.join(',');\r\n    }\r\n    return `${url}?${querystring(params).slice(1)}`;\r\n}\r\nasync function _openIframe(auth) {\r\n    const context = await _loadGapi(auth);\r\n    const gapi = _window().gapi;\r\n    _assert(gapi, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n    return context.open({\r\n        where: document.body,\r\n        url: getIframeUrl(auth),\r\n        messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\r\n        attributes: IFRAME_ATTRIBUTES,\r\n        dontclear: true\r\n    }, (iframe) => new Promise(async (resolve, reject) => {\r\n        await iframe.restyle({\r\n            // Prevent iframe from closing on mouse out.\r\n            setHideOnLeave: false\r\n        });\r\n        const networkError = _createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);\r\n        // Confirm iframe is correctly loaded.\r\n        // To fallback on failure, set a timeout.\r\n        const networkErrorTimer = _window().setTimeout(() => {\r\n            reject(networkError);\r\n        }, PING_TIMEOUT.get());\r\n        // Clear timer and resolve pending iframe ready promise.\r\n        function clearTimerAndResolve() {\r\n            _window().clearTimeout(networkErrorTimer);\r\n            resolve(iframe);\r\n        }\r\n        // This returns an IThenable. However the reject part does not call\r\n        // when the iframe is not loaded.\r\n        iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\r\n            reject(networkError);\r\n        });\r\n    }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst BASE_POPUP_OPTIONS = {\r\n    location: 'yes',\r\n    resizable: 'yes',\r\n    statusbar: 'yes',\r\n    toolbar: 'no'\r\n};\r\nconst DEFAULT_WIDTH = 500;\r\nconst DEFAULT_HEIGHT = 600;\r\nconst TARGET_BLANK = '_blank';\r\nconst FIREFOX_EMPTY_URL = 'http://localhost';\r\nclass AuthPopup {\r\n    constructor(window) {\r\n        this.window = window;\r\n        this.associatedEvent = null;\r\n    }\r\n    close() {\r\n        if (this.window) {\r\n            try {\r\n                this.window.close();\r\n            }\r\n            catch (e) { }\r\n        }\r\n    }\r\n}\r\nfunction _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {\r\n    const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\r\n    const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\r\n    let target = '';\r\n    const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top,\r\n        left });\r\n    // Chrome iOS 7 and 8 is returning an undefined popup win when target is\r\n    // specified, even though the popup is not necessarily blocked.\r\n    const ua = getUA().toLowerCase();\r\n    if (name) {\r\n        target = _isChromeIOS(ua) ? TARGET_BLANK : name;\r\n    }\r\n    if (_isFirefox(ua)) {\r\n        // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\r\n        url = url || FIREFOX_EMPTY_URL;\r\n        // Firefox disables by default scrolling on popup windows, which can create\r\n        // issues when the user has many Google accounts, for instance.\r\n        options.scrollbars = 'yes';\r\n    }\r\n    const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');\r\n    if (_isIOSStandalone(ua) && target !== '_self') {\r\n        openAsNewWindowIOS(url || '', target);\r\n        return new AuthPopup(null);\r\n    }\r\n    // about:blank getting sanitized causing browsers like IE/Edge to display\r\n    // brief error message before redirecting to handler.\r\n    const newWin = window.open(url || '', target, optionsString);\r\n    _assert(newWin, auth, \"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */);\r\n    // Flaky on IE edge, encapsulate with a try and catch.\r\n    try {\r\n        newWin.focus();\r\n    }\r\n    catch (e) { }\r\n    return new AuthPopup(newWin);\r\n}\r\nfunction openAsNewWindowIOS(url, target) {\r\n    const el = document.createElement('a');\r\n    el.href = url;\r\n    el.target = target;\r\n    const click = document.createEvent('MouseEvent');\r\n    click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);\r\n    el.dispatchEvent(click);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * URL for Authentication widget which will initiate the OAuth handshake\r\n *\r\n * @internal\r\n */\r\nconst WIDGET_PATH = '__/auth/handler';\r\n/**\r\n * URL for emulated environment\r\n *\r\n * @internal\r\n */\r\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\r\n/**\r\n * Fragment name for the App Check token that gets passed to the widget\r\n *\r\n * @internal\r\n */\r\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\r\nasync function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {\r\n    _assert(auth.config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n    _assert(auth.config.apiKey, auth, \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */);\r\n    const params = {\r\n        apiKey: auth.config.apiKey,\r\n        appName: auth.name,\r\n        authType,\r\n        redirectUrl,\r\n        v: SDK_VERSION,\r\n        eventId\r\n    };\r\n    if (provider instanceof FederatedAuthProvider) {\r\n        provider.setDefaultLanguage(auth.languageCode);\r\n        params.providerId = provider.providerId || '';\r\n        if (!isEmpty(provider.getCustomParameters())) {\r\n            params.customParameters = JSON.stringify(provider.getCustomParameters());\r\n        }\r\n        // TODO set additionalParams from the provider as well?\r\n        for (const [key, value] of Object.entries(additionalParams || {})) {\r\n            params[key] = value;\r\n        }\r\n    }\r\n    if (provider instanceof BaseOAuthProvider) {\r\n        const scopes = provider.getScopes().filter(scope => scope !== '');\r\n        if (scopes.length > 0) {\r\n            params.scopes = scopes.join(',');\r\n        }\r\n    }\r\n    if (auth.tenantId) {\r\n        params.tid = auth.tenantId;\r\n    }\r\n    // TODO: maybe set eid as endipointId\r\n    // TODO: maybe set fw as Frameworks.join(\",\")\r\n    const paramsDict = params;\r\n    for (const key of Object.keys(paramsDict)) {\r\n        if (paramsDict[key] === undefined) {\r\n            delete paramsDict[key];\r\n        }\r\n    }\r\n    // Sets the App Check token to pass to the widget\r\n    const appCheckToken = await auth._getAppCheckToken();\r\n    const appCheckTokenFragment = appCheckToken\r\n        ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\r\n        : '';\r\n    // Start at index 1 to skip the leading '&' in the query string\r\n    return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;\r\n}\r\nfunction getHandlerBase({ config }) {\r\n    if (!config.emulator) {\r\n        return `https://${config.authDomain}/${WIDGET_PATH}`;\r\n    }\r\n    return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The special web storage event\r\n *\r\n */\r\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\r\nclass BrowserPopupRedirectResolver {\r\n    constructor() {\r\n        this.eventManagers = {};\r\n        this.iframes = {};\r\n        this.originValidationPromises = {};\r\n        this._redirectPersistence = browserSessionPersistence;\r\n        this._completeRedirectFn = _getRedirectResult;\r\n        this._overrideRedirectResult = _overrideRedirectResult;\r\n    }\r\n    // Wrapping in async even though we don't await anywhere in order\r\n    // to make sure errors are raised as promise rejections\r\n    async _openPopup(auth, provider, authType, eventId) {\r\n        var _a;\r\n        debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');\r\n        const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n        return _open(auth, url, _generateEventId());\r\n    }\r\n    async _openRedirect(auth, provider, authType, eventId) {\r\n        await this._originValidation(auth);\r\n        const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n        _setWindowLocation(url);\r\n        return new Promise(() => { });\r\n    }\r\n    _initialize(auth) {\r\n        const key = auth._key();\r\n        if (this.eventManagers[key]) {\r\n            const { manager, promise } = this.eventManagers[key];\r\n            if (manager) {\r\n                return Promise.resolve(manager);\r\n            }\r\n            else {\r\n                debugAssert(promise, 'If manager is not set, promise should be');\r\n                return promise;\r\n            }\r\n        }\r\n        const promise = this.initAndGetManager(auth);\r\n        this.eventManagers[key] = { promise };\r\n        // If the promise is rejected, the key should be removed so that the\r\n        // operation can be retried later.\r\n        promise.catch(() => {\r\n            delete this.eventManagers[key];\r\n        });\r\n        return promise;\r\n    }\r\n    async initAndGetManager(auth) {\r\n        const iframe = await _openIframe(auth);\r\n        const manager = new AuthEventManager(auth);\r\n        iframe.register('authEvent', (iframeEvent) => {\r\n            _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, \"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */);\r\n            // TODO: Consider splitting redirect and popup events earlier on\r\n            const handled = manager.onEvent(iframeEvent.authEvent);\r\n            return { status: handled ? \"ACK\" /* GapiOutcome.ACK */ : \"ERROR\" /* GapiOutcome.ERROR */ };\r\n        }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n        this.eventManagers[auth._key()] = { manager };\r\n        this.iframes[auth._key()] = iframe;\r\n        return manager;\r\n    }\r\n    _isIframeWebStorageSupported(auth, cb) {\r\n        const iframe = this.iframes[auth._key()];\r\n        iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {\r\n            var _a;\r\n            const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];\r\n            if (isSupported !== undefined) {\r\n                cb(!!isSupported);\r\n            }\r\n            _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n    }\r\n    _originValidation(auth) {\r\n        const key = auth._key();\r\n        if (!this.originValidationPromises[key]) {\r\n            this.originValidationPromises[key] = _validateOrigin(auth);\r\n        }\r\n        return this.originValidationPromises[key];\r\n    }\r\n    get _shouldInitProactively() {\r\n        // Mobile browsers and Safari need to optimistically initialize\r\n        return _isMobileBrowser() || _isSafari() || _isIOS();\r\n    }\r\n}\r\n/**\r\n * An implementation of {@link PopupRedirectResolver} suitable for browser\r\n * based applications.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @public\r\n */\r\nconst browserPopupRedirectResolver = BrowserPopupRedirectResolver;\n\nclass MultiFactorAssertionImpl {\r\n    constructor(factorId) {\r\n        this.factorId = factorId;\r\n    }\r\n    _process(auth, session, displayName) {\r\n        switch (session.type) {\r\n            case \"enroll\" /* MultiFactorSessionType.ENROLL */:\r\n                return this._finalizeEnroll(auth, session.credential, displayName);\r\n            case \"signin\" /* MultiFactorSessionType.SIGN_IN */:\r\n                return this._finalizeSignIn(auth, session.credential);\r\n            default:\r\n                return debugFail('unexpected MultiFactorSessionType');\r\n        }\r\n    }\r\n}\n\n/**\r\n * {@inheritdoc PhoneMultiFactorAssertion}\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n    constructor(credential) {\r\n        super(\"phone\" /* FactorId.PHONE */);\r\n        this.credential = credential;\r\n    }\r\n    /** @internal */\r\n    static _fromCredential(credential) {\r\n        return new PhoneMultiFactorAssertionImpl(credential);\r\n    }\r\n    /** @internal */\r\n    _finalizeEnroll(auth, idToken, displayName) {\r\n        return finalizeEnrollPhoneMfa(auth, {\r\n            idToken,\r\n            displayName,\r\n            phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n        });\r\n    }\r\n    /** @internal */\r\n    _finalizeSignIn(auth, mfaPendingCredential) {\r\n        return finalizeSignInPhoneMfa(auth, {\r\n            mfaPendingCredential,\r\n            phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n        });\r\n    }\r\n}\r\n/**\r\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorGenerator {\r\n    constructor() { }\r\n    /**\r\n     * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\r\n     *\r\n     * @remarks\r\n     * This method does not work in a Node.js environment.\r\n     *\r\n     * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\r\n     * @returns A {@link PhoneMultiFactorAssertion} which can be used with\r\n     * {@link MultiFactorResolver.resolveSignIn}\r\n     */\r\n    static assertion(credential) {\r\n        return PhoneMultiFactorAssertionImpl._fromCredential(credential);\r\n    }\r\n}\r\n/**\r\n * The identifier of the phone second factor: `phone`.\r\n */\r\nPhoneMultiFactorGenerator.FACTOR_ID = 'phone';\n\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass TotpMultiFactorGenerator {\r\n    /**\r\n     * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\r\n     * the TOTP (time-based one-time password) second factor.\r\n     * This assertion is used to complete enrollment in TOTP second factor.\r\n     *\r\n     * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\r\n     * @param oneTimePassword One-time password from TOTP App.\r\n     * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n     * {@link MultiFactorUser.enroll}.\r\n     */\r\n    static assertionForEnrollment(secret, oneTimePassword) {\r\n        return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\r\n    }\r\n    /**\r\n     * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\r\n     * This assertion is used to complete signIn with TOTP as the second factor.\r\n     *\r\n     * @param enrollmentId identifies the enrolled TOTP second factor.\r\n     * @param oneTimePassword One-time password from TOTP App.\r\n     * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n     * {@link MultiFactorResolver.resolveSignIn}.\r\n     */\r\n    static assertionForSignIn(enrollmentId, oneTimePassword) {\r\n        return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);\r\n    }\r\n    /**\r\n     * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\r\n     * Creates a TOTP secret as part of enrolling a TOTP second factor.\r\n     * Used for generating a QR code URL or inputting into a TOTP app.\r\n     * This method uses the auth instance corresponding to the user in the multiFactorSession.\r\n     *\r\n     * @param session The {@link MultiFactorSession} that the user is part of.\r\n     * @returns A promise to {@link TotpSecret}.\r\n     */\r\n    static async generateSecret(session) {\r\n        var _a;\r\n        const mfaSession = session;\r\n        _assert(typeof ((_a = mfaSession.user) === null || _a === void 0 ? void 0 : _a.auth) !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n        const response = await startEnrollTotpMfa(mfaSession.user.auth, {\r\n            idToken: mfaSession.credential,\r\n            totpEnrollmentInfo: {}\r\n        });\r\n        return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.user.auth);\r\n    }\r\n}\r\n/**\r\n * The identifier of the TOTP second factor: `totp`.\r\n */\r\nTotpMultiFactorGenerator.FACTOR_ID = \"totp\" /* FactorId.TOTP */;\r\nclass TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n    constructor(otp, enrollmentId, secret) {\r\n        super(\"totp\" /* FactorId.TOTP */);\r\n        this.otp = otp;\r\n        this.enrollmentId = enrollmentId;\r\n        this.secret = secret;\r\n    }\r\n    /** @internal */\r\n    static _fromSecret(secret, otp) {\r\n        return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\r\n    }\r\n    /** @internal */\r\n    static _fromEnrollmentId(enrollmentId, otp) {\r\n        return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\r\n    }\r\n    /** @internal */\r\n    async _finalizeEnroll(auth, idToken, displayName) {\r\n        _assert(typeof this.secret !== 'undefined', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        return finalizeEnrollTotpMfa(auth, {\r\n            idToken,\r\n            displayName,\r\n            totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\r\n        });\r\n    }\r\n    /** @internal */\r\n    async _finalizeSignIn(auth, mfaPendingCredential) {\r\n        _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n        const totpVerificationInfo = { verificationCode: this.otp };\r\n        return finalizeSignInTotpMfa(auth, {\r\n            mfaPendingCredential,\r\n            mfaEnrollmentId: this.enrollmentId,\r\n            totpVerificationInfo\r\n        });\r\n    }\r\n}\r\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * Stores the shared secret key and other parameters to generate time-based OTPs.\r\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\r\n * @public\r\n */\r\nclass TotpSecret {\r\n    // The public members are declared outside the constructor so the docs can be generated.\r\n    constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {\r\n        this.sessionInfo = sessionInfo;\r\n        this.auth = auth;\r\n        this.secretKey = secretKey;\r\n        this.hashingAlgorithm = hashingAlgorithm;\r\n        this.codeLength = codeLength;\r\n        this.codeIntervalSeconds = codeIntervalSeconds;\r\n        this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\r\n    }\r\n    /** @internal */\r\n    static _fromStartTotpMfaEnrollmentResponse(response, auth) {\r\n        return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth);\r\n    }\r\n    /** @internal */\r\n    _makeTotpVerificationInfo(otp) {\r\n        return { sessionInfo: this.sessionInfo, verificationCode: otp };\r\n    }\r\n    /**\r\n     * Returns a QR code URL as described in\r\n     * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\r\n     * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\r\n     * If the optional parameters are unspecified, an accountName of <userEmail> and issuer of <firebaseAppName> are used.\r\n     *\r\n     * @param accountName the name of the account/app along with a user identifier.\r\n     * @param issuer issuer of the TOTP (likely the app name).\r\n     * @returns A QR code URL string.\r\n     */\r\n    generateQrCodeUrl(accountName, issuer) {\r\n        var _a;\r\n        let useDefaults = false;\r\n        if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\r\n            useDefaults = true;\r\n        }\r\n        if (useDefaults) {\r\n            if (_isEmptyString(accountName)) {\r\n                accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';\r\n            }\r\n            if (_isEmptyString(issuer)) {\r\n                issuer = this.auth.name;\r\n            }\r\n        }\r\n        return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\r\n    }\r\n}\r\n/** @internal */\r\nfunction _isEmptyString(input) {\r\n    return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;\r\n}\n\nvar name = \"@firebase/auth\";\nvar version = \"1.1.0\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthInterop {\r\n    constructor(auth) {\r\n        this.auth = auth;\r\n        this.internalListeners = new Map();\r\n    }\r\n    getUid() {\r\n        var _a;\r\n        this.assertAuthConfigured();\r\n        return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;\r\n    }\r\n    async getToken(forceRefresh) {\r\n        this.assertAuthConfigured();\r\n        await this.auth._initializationPromise;\r\n        if (!this.auth.currentUser) {\r\n            return null;\r\n        }\r\n        const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\r\n        return { accessToken };\r\n    }\r\n    addAuthTokenListener(listener) {\r\n        this.assertAuthConfigured();\r\n        if (this.internalListeners.has(listener)) {\r\n            return;\r\n        }\r\n        const unsubscribe = this.auth.onIdTokenChanged(user => {\r\n            listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);\r\n        });\r\n        this.internalListeners.set(listener, unsubscribe);\r\n        this.updateProactiveRefresh();\r\n    }\r\n    removeAuthTokenListener(listener) {\r\n        this.assertAuthConfigured();\r\n        const unsubscribe = this.internalListeners.get(listener);\r\n        if (!unsubscribe) {\r\n            return;\r\n        }\r\n        this.internalListeners.delete(listener);\r\n        unsubscribe();\r\n        this.updateProactiveRefresh();\r\n    }\r\n    assertAuthConfigured() {\r\n        _assert(this.auth._initializationPromise, \"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);\r\n    }\r\n    updateProactiveRefresh() {\r\n        if (this.internalListeners.size > 0) {\r\n            this.auth._startProactiveRefresh();\r\n        }\r\n        else {\r\n            this.auth._stopProactiveRefresh();\r\n        }\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getVersionForPlatform(clientPlatform) {\r\n    switch (clientPlatform) {\r\n        case \"Node\" /* ClientPlatform.NODE */:\r\n            return 'node';\r\n        case \"ReactNative\" /* ClientPlatform.REACT_NATIVE */:\r\n            return 'rn';\r\n        case \"Worker\" /* ClientPlatform.WORKER */:\r\n            return 'webworker';\r\n        case \"Cordova\" /* ClientPlatform.CORDOVA */:\r\n            return 'cordova';\r\n        default:\r\n            return undefined;\r\n    }\r\n}\r\n/** @internal */\r\nfunction registerAuth(clientPlatform) {\r\n    _registerComponent(new Component(\"auth\" /* _ComponentName.AUTH */, (container, { options: deps }) => {\r\n        const app = container.getProvider('app').getImmediate();\r\n        const heartbeatServiceProvider = container.getProvider('heartbeat');\r\n        const appCheckServiceProvider = container.getProvider('app-check-internal');\r\n        const { apiKey, authDomain } = app.options;\r\n        _assert(apiKey && !apiKey.includes(':'), \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });\r\n        const config = {\r\n            apiKey,\r\n            authDomain,\r\n            clientPlatform,\r\n            apiHost: \"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */,\r\n            tokenApiHost: \"securetoken.googleapis.com\" /* DefaultConfig.TOKEN_API_HOST */,\r\n            apiScheme: \"https\" /* DefaultConfig.API_SCHEME */,\r\n            sdkClientVersion: _getClientVersion(clientPlatform)\r\n        };\r\n        const authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);\r\n        _initializeAuthInstance(authInstance, deps);\r\n        return authInstance;\r\n    }, \"PUBLIC\" /* ComponentType.PUBLIC */)\r\n        /**\r\n         * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\r\n         * For why we do this, See go/firebase-next-auth-init\r\n         */\r\n        .setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */)\r\n        /**\r\n         * Because all firebase products that depend on auth depend on auth-internal directly,\r\n         * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\r\n         */\r\n        .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {\r\n        const authInternalProvider = container.getProvider(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */);\r\n        authInternalProvider.initialize();\r\n    }));\r\n    _registerComponent(new Component(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */, container => {\r\n        const auth = _castAuth(container.getProvider(\"auth\" /* _ComponentName.AUTH */).getImmediate());\r\n        return (auth => new AuthInterop(auth))(auth);\r\n    }, \"PRIVATE\" /* ComponentType.PRIVATE */).setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */));\r\n    registerVersion(name, version, getVersionForPlatform(clientPlatform));\r\n    // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n    registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\r\nconst authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\r\nlet lastPostedIdToken = null;\r\nconst mintCookieFactory = (url) => async (user) => {\r\n    const idTokenResult = user && (await user.getIdTokenResult());\r\n    const idTokenAge = idTokenResult &&\r\n        (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;\r\n    if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\r\n        return;\r\n    }\r\n    // Specifically trip null => undefined when logged out, to delete any existing cookie\r\n    const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;\r\n    if (lastPostedIdToken === idToken) {\r\n        return;\r\n    }\r\n    lastPostedIdToken = idToken;\r\n    await fetch(url, {\r\n        method: idToken ? 'POST' : 'DELETE',\r\n        headers: idToken\r\n            ? {\r\n                'Authorization': `Bearer ${idToken}`\r\n            }\r\n            : {}\r\n    });\r\n};\r\n/**\r\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\r\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\r\n *\r\n * @param app - The Firebase App.\r\n *\r\n * @public\r\n */\r\nfunction getAuth(app = getApp()) {\r\n    const provider = _getProvider(app, 'auth');\r\n    if (provider.isInitialized()) {\r\n        return provider.getImmediate();\r\n    }\r\n    const auth = initializeAuth(app, {\r\n        popupRedirectResolver: browserPopupRedirectResolver,\r\n        persistence: [\r\n            indexedDBLocalPersistence,\r\n            browserLocalPersistence,\r\n            browserSessionPersistence\r\n        ]\r\n    });\r\n    const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');\r\n    if (authTokenSyncUrl) {\r\n        const mintCookie = mintCookieFactory(authTokenSyncUrl);\r\n        beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));\r\n        onIdTokenChanged(auth, user => mintCookie(user));\r\n    }\r\n    const authEmulatorHost = getDefaultEmulatorHost('auth');\r\n    if (authEmulatorHost) {\r\n        connectAuthEmulator(auth, `http://${authEmulatorHost}`);\r\n    }\r\n    return auth;\r\n}\r\nregisterAuth(\"Browser\" /* ClientPlatform.BROWSER */);\n\nexport { signInWithCredential as $, ActionCodeOperation as A, signOut as B, deleteUser as C, debugErrorMap as D, prodErrorMap as E, FactorId as F, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as G, initializeAuth as H, connectAuthEmulator as I, AuthCredential as J, EmailAuthCredential as K, OAuthCredential as L, PhoneAuthCredential as M, inMemoryPersistence as N, OperationType as O, PhoneAuthProvider as P, EmailAuthProvider as Q, RecaptchaVerifier as R, SignInMethod as S, TotpMultiFactorGenerator as T, FacebookAuthProvider as U, GoogleAuthProvider as V, GithubAuthProvider as W, OAuthProvider as X, SAMLAuthProvider as Y, TwitterAuthProvider as Z, signInAnonymously as _, browserSessionPersistence as a, linkWithCredential as a0, reauthenticateWithCredential as a1, signInWithCustomToken as a2, sendPasswordResetEmail as a3, confirmPasswordReset as a4, applyActionCode as a5, checkActionCode as a6, verifyPasswordResetCode as a7, createUserWithEmailAndPassword as a8, signInWithEmailAndPassword as a9, _assert as aA, AuthEventManager as aB, _getInstance as aC, _persistenceKeyName as aD, _getRedirectResult as aE, _overrideRedirectResult as aF, _clearRedirectOutcomes as aG, _castAuth as aH, UserImpl as aI, AuthImpl as aJ, _getClientVersion as aK, _generateEventId as aL, AuthPopup as aM, FetchProvider as aN, SAMLAuthCredential as aO, sendSignInLinkToEmail as aa, isSignInWithEmailLink as ab, signInWithEmailLink as ac, fetchSignInMethodsForEmail as ad, sendEmailVerification as ae, verifyBeforeUpdateEmail as af, ActionCodeURL as ag, parseActionCodeURL as ah, updateProfile as ai, updateEmail as aj, updatePassword as ak, getIdToken as al, getIdTokenResult as am, unlink as an, getAdditionalUserInfo as ao, reload as ap, getMultiFactorResolver as aq, multiFactor as ar, debugAssert as as, _isIOS as at, _isAndroid as au, _fail as av, _getRedirectUrl as aw, _getProjectConfig as ax, _isIOS7Or8 as ay, _createError as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, TotpSecret as n, getAuth as o, ProviderId as p, setPersistence as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, initializeRecaptchaConfig as t, updatePhoneNumber as u, onIdTokenChanged as v, beforeAuthStateChanged as w, onAuthStateChanged as x, useDeviceLanguage as y, updateCurrentUser as z };\n//# sourceMappingURL=index-e24386e7.js.map\n","/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n  for (var i = 1; i < arguments.length; i++) {\n    var source = arguments[i];\n    for (var key in source) {\n      target[key] = source[key];\n    }\n  }\n  return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n  read: function (value) {\n    if (value[0] === '\"') {\n      value = value.slice(1, -1);\n    }\n    return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n  },\n  write: function (value) {\n    return encodeURIComponent(value).replace(\n      /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n      decodeURIComponent\n    )\n  }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n  function set (name, value, attributes) {\n    if (typeof document === 'undefined') {\n      return\n    }\n\n    attributes = assign({}, defaultAttributes, attributes);\n\n    if (typeof attributes.expires === 'number') {\n      attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n    }\n    if (attributes.expires) {\n      attributes.expires = attributes.expires.toUTCString();\n    }\n\n    name = encodeURIComponent(name)\n      .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n      .replace(/[()]/g, escape);\n\n    var stringifiedAttributes = '';\n    for (var attributeName in attributes) {\n      if (!attributes[attributeName]) {\n        continue\n      }\n\n      stringifiedAttributes += '; ' + attributeName;\n\n      if (attributes[attributeName] === true) {\n        continue\n      }\n\n      // Considers RFC 6265 section 5.2:\n      // ...\n      // 3.  If the remaining unparsed-attributes contains a %x3B (\";\")\n      //     character:\n      // Consume the characters of the unparsed-attributes up to,\n      // not including, the first %x3B (\";\") character.\n      // ...\n      stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n    }\n\n    return (document.cookie =\n      name + '=' + converter.write(value, name) + stringifiedAttributes)\n  }\n\n  function get (name) {\n    if (typeof document === 'undefined' || (arguments.length && !name)) {\n      return\n    }\n\n    // To prevent the for loop in the first place assign an empty array\n    // in case there are no cookies at all.\n    var cookies = document.cookie ? document.cookie.split('; ') : [];\n    var jar = {};\n    for (var i = 0; i < cookies.length; i++) {\n      var parts = cookies[i].split('=');\n      var value = parts.slice(1).join('=');\n\n      try {\n        var found = decodeURIComponent(parts[0]);\n        jar[found] = converter.read(value, found);\n\n        if (name === found) {\n          break\n        }\n      } catch (e) {}\n    }\n\n    return name ? jar[name] : jar\n  }\n\n  return Object.create(\n    {\n      set,\n      get,\n      remove: function (name, attributes) {\n        set(\n          name,\n          '',\n          assign({}, attributes, {\n            expires: -1\n          })\n        );\n      },\n      withAttributes: function (attributes) {\n        return init(this.converter, assign({}, this.attributes, attributes))\n      },\n      withConverter: function (converter) {\n        return init(assign({}, this.converter, converter), this.attributes)\n      }\n    },\n    {\n      attributes: { value: Object.freeze(defaultAttributes) },\n      converter: { value: Object.freeze(converter) }\n    }\n  )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport { api as default };\n","var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nvar esm = {};\n\n/*\n\n Copyright The Closure Library Authors.\n SPDX-License-Identifier: Apache-2.0\n*/\n\nvar k,goog=goog||{},l=commonjsGlobal||self;function aa(a){var b=typeof a;b=\"object\"!=b?b:a?Array.isArray(a)?\"array\":b:\"null\";return \"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function p(a){var b=typeof a;return \"object\"==b&&null!=a||\"function\"==b}function ba(a){return Object.prototype.hasOwnProperty.call(a,ca)&&a[ca]||(a[ca]=++da)}var ca=\"closure_uid_\"+(1E9*Math.random()>>>0),da=0;function ea(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction fa(a,b,c){if(!a)throw Error();if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(e,d);return a.apply(b,e)}}return function(){return a.apply(b,arguments)}}function q(a,b,c){Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf(\"native code\")?q=ea:q=fa;return q.apply(null,arguments)}\nfunction ha(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var d=c.slice();d.push.apply(d,arguments);return a.apply(this,d)}}function r(a,b){function c(){}c.prototype=b.prototype;a.$=b.prototype;a.prototype=new c;a.prototype.constructor=a;a.ac=function(d,e,f){for(var h=Array(arguments.length-2),n=2;n<arguments.length;n++)h[n-2]=arguments[n];return b.prototype[e].apply(d,h)};}function v(){this.s=this.s;this.o=this.o;}var ia=0;v.prototype.s=!1;v.prototype.sa=function(){if(!this.s&&(this.s=!0,this.N(),0!=ia)){ba(this);}};v.prototype.N=function(){if(this.o)for(;this.o.length;)this.o.shift()();};const ka=Array.prototype.indexOf?function(a,b){return Array.prototype.indexOf.call(a,b,void 0)}:function(a,b){if(\"string\"===typeof a)return \"string\"!==typeof b||1!=b.length?-1:a.indexOf(b,0);for(let c=0;c<a.length;c++)if(c in a&&a[c]===b)return c;return -1};function ma(a){const b=a.length;if(0<b){const c=Array(b);for(let d=0;d<b;d++)c[d]=a[d];return c}return []}\nfunction na(a,b){for(let c=1;c<arguments.length;c++){const d=arguments[c];if(aa(d)){const e=a.length||0,f=d.length||0;a.length=e+f;for(let h=0;h<f;h++)a[e+h]=d[h];}else a.push(d);}}function w(a,b){this.type=a;this.g=this.target=b;this.defaultPrevented=!1;}w.prototype.h=function(){this.defaultPrevented=!0;};var oa=function(){if(!l.addEventListener||!Object.defineProperty)return !1;var a=!1,b=Object.defineProperty({},\"passive\",{get:function(){a=!0;}});try{l.addEventListener(\"test\",()=>{},b),l.removeEventListener(\"test\",()=>{},b);}catch(c){}return a}();function x(a){return /^[\\s\\xa0]*$/.test(a)}function pa(){var a=l.navigator;return a&&(a=a.userAgent)?a:\"\"}function y(a){return -1!=pa().indexOf(a)}function qa(a){qa[\" \"](a);return a}qa[\" \"]=function(){};function ra(a,b){var c=sa;return Object.prototype.hasOwnProperty.call(c,a)?c[a]:c[a]=b(a)}var ta=y(\"Opera\"),z=y(\"Trident\")||y(\"MSIE\"),ua=y(\"Edge\"),va=ua||z,wa=y(\"Gecko\")&&!(-1!=pa().toLowerCase().indexOf(\"webkit\")&&!y(\"Edge\"))&&!(y(\"Trident\")||y(\"MSIE\"))&&!y(\"Edge\"),xa=-1!=pa().toLowerCase().indexOf(\"webkit\")&&!y(\"Edge\");function ya(){var a=l.document;return a?a.documentMode:void 0}var za;\na:{var Aa=\"\",Ba=function(){var a=pa();if(wa)return /rv:([^\\);]+)(\\)|;)/.exec(a);if(ua)return /Edge\\/([\\d\\.]+)/.exec(a);if(z)return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(a);if(xa)return /WebKit\\/(\\S+)/.exec(a);if(ta)return /(?:Version)[ \\/]?(\\S+)/.exec(a)}();Ba&&(Aa=Ba?Ba[1]:\"\");if(z){var Ca=ya();if(null!=Ca&&Ca>parseFloat(Aa)){za=String(Ca);break a}}za=Aa;}var Da;if(l.document&&z){var Ea=ya();Da=Ea?Ea:parseInt(za,10)||void 0;}else Da=void 0;var Fa=Da;function A(a,b){w.call(this,a?a.type:\"\");this.relatedTarget=this.g=this.target=null;this.button=this.screenY=this.screenX=this.clientY=this.clientX=0;this.key=\"\";this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.state=null;this.pointerId=0;this.pointerType=\"\";this.i=null;if(a){var c=this.type=a.type,d=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.g=b;if(b=a.relatedTarget){if(wa){a:{try{qa(b.nodeName);var e=!0;break a}catch(f){}e=\n!1;}e||(b=null);}}else \"mouseover\"==c?b=a.fromElement:\"mouseout\"==c&&(b=a.toElement);this.relatedTarget=b;d?(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0):(this.clientX=void 0!==a.clientX?a.clientX:a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0);this.button=a.button;this.key=a.key||\"\";this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=\na.shiftKey;this.metaKey=a.metaKey;this.pointerId=a.pointerId||0;this.pointerType=\"string\"===typeof a.pointerType?a.pointerType:Ga[a.pointerType]||\"\";this.state=a.state;this.i=a;a.defaultPrevented&&A.$.h.call(this);}}r(A,w);var Ga={2:\"touch\",3:\"pen\",4:\"mouse\"};A.prototype.h=function(){A.$.h.call(this);var a=this.i;a.preventDefault?a.preventDefault():a.returnValue=!1;};var Ha=\"closure_listenable_\"+(1E6*Math.random()|0);var Ia=0;function Ja(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.la=e;this.key=++Ia;this.fa=this.ia=!1;}function Ka(a){a.fa=!0;a.listener=null;a.proxy=null;a.src=null;a.la=null;}function Na(a,b,c){for(const d in a)b.call(c,a[d],d,a);}function Oa(a,b){for(const c in a)b.call(void 0,a[c],c,a);}function Pa(a){const b={};for(const c in a)b[c]=a[c];return b}const Qa=\"constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf\".split(\" \");function Ra(a,b){let c,d;for(let e=1;e<arguments.length;e++){d=arguments[e];for(c in d)a[c]=d[c];for(let f=0;f<Qa.length;f++)c=Qa[f],Object.prototype.hasOwnProperty.call(d,c)&&(a[c]=d[c]);}}function Sa(a){this.src=a;this.g={};this.h=0;}Sa.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.g[f];a||(a=this.g[f]=[],this.h++);var h=Ta(a,b,d,e);-1<h?(b=a[h],c||(b.ia=!1)):(b=new Ja(b,this.src,f,!!d,e),b.ia=c,a.push(b));return b};function Ua(a,b){var c=b.type;if(c in a.g){var d=a.g[c],e=ka(d,b),f;(f=0<=e)&&Array.prototype.splice.call(d,e,1);f&&(Ka(b),0==a.g[c].length&&(delete a.g[c],a.h--));}}\nfunction Ta(a,b,c,d){for(var e=0;e<a.length;++e){var f=a[e];if(!f.fa&&f.listener==b&&f.capture==!!c&&f.la==d)return e}return -1}var Va=\"closure_lm_\"+(1E6*Math.random()|0),Wa={};function Ya(a,b,c,d,e){if(d&&d.once)return Za(a,b,c,d,e);if(Array.isArray(b)){for(var f=0;f<b.length;f++)Ya(a,b[f],c,d,e);return null}c=$a(c);return a&&a[Ha]?a.O(b,c,p(d)?!!d.capture:!!d,e):ab(a,b,c,!1,d,e)}\nfunction ab(a,b,c,d,e,f){if(!b)throw Error(\"Invalid event type\");var h=p(e)?!!e.capture:!!e,n=bb(a);n||(a[Va]=n=new Sa(a));c=n.add(b,c,d,h,f);if(c.proxy)return c;d=cb();c.proxy=d;d.src=a;d.listener=c;if(a.addEventListener)oa||(e=h),void 0===e&&(e=!1),a.addEventListener(b.toString(),d,e);else if(a.attachEvent)a.attachEvent(db(b.toString()),d);else if(a.addListener&&a.removeListener)a.addListener(d);else throw Error(\"addEventListener and attachEvent are unavailable.\");return c}\nfunction cb(){function a(c){return b.call(a.src,a.listener,c)}const b=eb;return a}function Za(a,b,c,d,e){if(Array.isArray(b)){for(var f=0;f<b.length;f++)Za(a,b[f],c,d,e);return null}c=$a(c);return a&&a[Ha]?a.P(b,c,p(d)?!!d.capture:!!d,e):ab(a,b,c,!0,d,e)}\nfunction fb(a,b,c,d,e){if(Array.isArray(b))for(var f=0;f<b.length;f++)fb(a,b[f],c,d,e);else (d=p(d)?!!d.capture:!!d,c=$a(c),a&&a[Ha])?(a=a.i,b=String(b).toString(),b in a.g&&(f=a.g[b],c=Ta(f,c,d,e),-1<c&&(Ka(f[c]),Array.prototype.splice.call(f,c,1),0==f.length&&(delete a.g[b],a.h--)))):a&&(a=bb(a))&&(b=a.g[b.toString()],a=-1,b&&(a=Ta(b,c,d,e)),(c=-1<a?b[a]:null)&&gb(c));}\nfunction gb(a){if(\"number\"!==typeof a&&a&&!a.fa){var b=a.src;if(b&&b[Ha])Ua(b.i,a);else {var c=a.type,d=a.proxy;b.removeEventListener?b.removeEventListener(c,d,a.capture):b.detachEvent?b.detachEvent(db(c),d):b.addListener&&b.removeListener&&b.removeListener(d);(c=bb(b))?(Ua(c,a),0==c.h&&(c.src=null,b[Va]=null)):Ka(a);}}}function db(a){return a in Wa?Wa[a]:Wa[a]=\"on\"+a}function eb(a,b){if(a.fa)a=!0;else {b=new A(b,this);var c=a.listener,d=a.la||a.src;a.ia&&gb(a);a=c.call(d,b);}return a}\nfunction bb(a){a=a[Va];return a instanceof Sa?a:null}var hb=\"__closure_events_fn_\"+(1E9*Math.random()>>>0);function $a(a){if(\"function\"===typeof a)return a;a[hb]||(a[hb]=function(b){return a.handleEvent(b)});return a[hb]}function B(){v.call(this);this.i=new Sa(this);this.S=this;this.J=null;}r(B,v);B.prototype[Ha]=!0;B.prototype.removeEventListener=function(a,b,c,d){fb(this,a,b,c,d);};\nfunction C(a,b){var c,d=a.J;if(d)for(c=[];d;d=d.J)c.push(d);a=a.S;d=b.type||b;if(\"string\"===typeof b)b=new w(b,a);else if(b instanceof w)b.target=b.target||a;else {var e=b;b=new w(d,a);Ra(b,e);}e=!0;if(c)for(var f=c.length-1;0<=f;f--){var h=b.g=c[f];e=ib(h,d,!0,b)&&e;}h=b.g=a;e=ib(h,d,!0,b)&&e;e=ib(h,d,!1,b)&&e;if(c)for(f=0;f<c.length;f++)h=b.g=c[f],e=ib(h,d,!1,b)&&e;}\nB.prototype.N=function(){B.$.N.call(this);if(this.i){var a=this.i,c;for(c in a.g){for(var d=a.g[c],e=0;e<d.length;e++)Ka(d[e]);delete a.g[c];a.h--;}}this.J=null;};B.prototype.O=function(a,b,c,d){return this.i.add(String(a),b,!1,c,d)};B.prototype.P=function(a,b,c,d){return this.i.add(String(a),b,!0,c,d)};\nfunction ib(a,b,c,d){b=a.i.g[String(b)];if(!b)return !0;b=b.concat();for(var e=!0,f=0;f<b.length;++f){var h=b[f];if(h&&!h.fa&&h.capture==c){var n=h.listener,t=h.la||h.src;h.ia&&Ua(a.i,h);e=!1!==n.call(t,d)&&e;}}return e&&!d.defaultPrevented}var jb=l.JSON.stringify;class kb{constructor(a,b){this.i=a;this.j=b;this.h=0;this.g=null;}get(){let a;0<this.h?(this.h--,a=this.g,this.g=a.next,a.next=null):a=this.i();return a}}function lb(){var a=mb;let b=null;a.g&&(b=a.g,a.g=a.g.next,a.g||(a.h=null),b.next=null);return b}class nb{constructor(){this.h=this.g=null;}add(a,b){const c=ob.get();c.set(a,b);this.h?this.h.next=c:this.g=c;this.h=c;}}var ob=new kb(()=>new pb,a=>a.reset());class pb{constructor(){this.next=this.g=this.h=null;}set(a,b){this.h=a;this.g=b;this.next=null;}reset(){this.next=this.g=this.h=null;}}function qb(a){var b=1;a=a.split(\":\");const c=[];for(;0<b&&a.length;)c.push(a.shift()),b--;a.length&&c.push(a.join(\":\"));return c}function rb(a){l.setTimeout(()=>{throw a;},0);}let sb,tb=!1,mb=new nb,vb=()=>{const a=l.Promise.resolve(void 0);sb=()=>{a.then(ub);};};var ub=()=>{for(var a;a=lb();){try{a.h.call(a.g);}catch(c){rb(c);}var b=ob;b.j(a);100>b.h&&(b.h++,a.next=b.g,b.g=a);}tb=!1;};function wb(a,b){B.call(this);this.h=a||1;this.g=b||l;this.j=q(this.qb,this);this.l=Date.now();}r(wb,B);k=wb.prototype;k.ga=!1;k.T=null;k.qb=function(){if(this.ga){var a=Date.now()-this.l;0<a&&a<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-a):(this.T&&(this.g.clearTimeout(this.T),this.T=null),C(this,\"tick\"),this.ga&&(xb(this),this.start()));}};k.start=function(){this.ga=!0;this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now());};\nfunction xb(a){a.ga=!1;a.T&&(a.g.clearTimeout(a.T),a.T=null);}k.N=function(){wb.$.N.call(this);xb(this);delete this.g;};function yb(a,b,c){if(\"function\"===typeof a)c&&(a=q(a,c));else if(a&&\"function\"==typeof a.handleEvent)a=q(a.handleEvent,a);else throw Error(\"Invalid listener argument\");return 2147483647<Number(b)?-1:l.setTimeout(a,b||0)}function zb(a){a.g=yb(()=>{a.g=null;a.i&&(a.i=!1,zb(a));},a.j);const b=a.h;a.h=null;a.m.apply(null,b);}class Ab extends v{constructor(a,b){super();this.m=a;this.j=b;this.h=null;this.i=!1;this.g=null;}l(a){this.h=arguments;this.g?this.i=!0:zb(this);}N(){super.N();this.g&&(l.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null);}}function Bb(a){v.call(this);this.h=a;this.g={};}r(Bb,v);var Cb=[];function Db(a,b,c,d){Array.isArray(c)||(c&&(Cb[0]=c.toString()),c=Cb);for(var e=0;e<c.length;e++){var f=Ya(b,c[e],d||a.handleEvent,!1,a.h||a);if(!f)break;a.g[f.key]=f;}}function Fb(a){Na(a.g,function(b,c){this.g.hasOwnProperty(c)&&gb(b);},a);a.g={};}Bb.prototype.N=function(){Bb.$.N.call(this);Fb(this);};Bb.prototype.handleEvent=function(){throw Error(\"EventHandler.handleEvent not implemented\");};function Gb(){this.g=!0;}Gb.prototype.Ea=function(){this.g=!1;};function Hb(a,b,c,d,e,f){a.info(function(){if(a.g)if(f){var h=\"\";for(var n=f.split(\"&\"),t=0;t<n.length;t++){var m=n[t].split(\"=\");if(1<m.length){var u=m[0];m=m[1];var L=u.split(\"_\");h=2<=L.length&&\"type\"==L[1]?h+(u+\"=\"+m+\"&\"):h+(u+\"=redacted&\");}}}else h=null;else h=f;return \"XMLHTTP REQ (\"+d+\") [attempt \"+e+\"]: \"+b+\"\\n\"+c+\"\\n\"+h});}\nfunction Ib(a,b,c,d,e,f,h){a.info(function(){return \"XMLHTTP RESP (\"+d+\") [ attempt \"+e+\"]: \"+b+\"\\n\"+c+\"\\n\"+f+\" \"+h});}function D(a,b,c,d){a.info(function(){return \"XMLHTTP TEXT (\"+b+\"): \"+Jb(a,c)+(d?\" \"+d:\"\")});}function Kb(a,b){a.info(function(){return \"TIMEOUT: \"+b});}Gb.prototype.info=function(){};\nfunction Jb(a,b){if(!a.g)return b;if(!b)return null;try{var c=JSON.parse(b);if(c)for(a=0;a<c.length;a++)if(Array.isArray(c[a])){var d=c[a];if(!(2>d.length)){var e=d[1];if(Array.isArray(e)&&!(1>e.length)){var f=e[0];if(\"noop\"!=f&&\"stop\"!=f&&\"close\"!=f)for(var h=1;h<e.length;h++)e[h]=\"\";}}}return jb(c)}catch(n){return b}}var E={},Lb=null;function Mb(){return Lb=Lb||new B}E.Ta=\"serverreachability\";function Nb(a){w.call(this,E.Ta,a);}r(Nb,w);function Ob(a){const b=Mb();C(b,new Nb(b));}E.STAT_EVENT=\"statevent\";function Pb(a,b){w.call(this,E.STAT_EVENT,a);this.stat=b;}r(Pb,w);function F(a){const b=Mb();C(b,new Pb(b,a));}E.Ua=\"timingevent\";function Qb(a,b){w.call(this,E.Ua,a);this.size=b;}r(Qb,w);\nfunction Rb(a,b){if(\"function\"!==typeof a)throw Error(\"Fn must not be null and must be a function\");return l.setTimeout(function(){a();},b)}var Sb={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9};var Tb={wb:\"complete\",Sb:\"success\",Ra:\"error\",Qa:\"abort\",Kb:\"ready\",Lb:\"readystatechange\",TIMEOUT:\"timeout\",Gb:\"incrementaldata\",Jb:\"progress\",zb:\"downloadprogress\",$b:\"uploadprogress\"};function Ub(){}Ub.prototype.h=null;function Vb(a){return a.h||(a.h=a.i())}function Wb(){}var Xb={OPEN:\"a\",vb:\"b\",Ra:\"c\",Hb:\"d\"};function Yb(){w.call(this,\"d\");}r(Yb,w);function Zb(){w.call(this,\"c\");}r(Zb,w);var $b;function ac(){}r(ac,Ub);ac.prototype.g=function(){return new XMLHttpRequest};ac.prototype.i=function(){return {}};$b=new ac;function bc(a,b,c,d){this.l=a;this.j=b;this.m=c;this.W=d||1;this.U=new Bb(this);this.P=cc;a=va?125:void 0;this.V=new wb(a);this.I=null;this.i=!1;this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null;this.F=[];this.g=null;this.C=0;this.o=this.u=null;this.ca=-1;this.J=!1;this.O=0;this.M=null;this.ba=this.K=this.aa=this.S=!1;this.h=new dc;}function dc(){this.i=null;this.g=\"\";this.h=!1;}var cc=45E3,ec={},fc={};k=bc.prototype;k.setTimeout=function(a){this.P=a;};\nfunction gc(a,b,c){a.L=1;a.v=hc(G(b));a.s=c;a.S=!0;ic(a,null);}function ic(a,b){a.G=Date.now();jc(a);a.A=G(a.v);var c=a.A,d=a.W;Array.isArray(d)||(d=[String(d)]);kc(c.i,\"t\",d);a.C=0;c=a.l.J;a.h=new dc;a.g=lc(a.l,c?b:null,!a.s);0<a.O&&(a.M=new Ab(q(a.Pa,a,a.g),a.O));Db(a.U,a.g,\"readystatechange\",a.nb);b=a.I?Pa(a.I):{};a.s?(a.u||(a.u=\"POST\"),b[\"Content-Type\"]=\"application/x-www-form-urlencoded\",a.g.ha(a.A,a.u,a.s,b)):(a.u=\"GET\",a.g.ha(a.A,a.u,null,b));Ob();Hb(a.j,a.u,a.A,a.m,a.W,a.s);}\nk.nb=function(a){a=a.target;const b=this.M;b&&3==H(a)?b.l():this.Pa(a);};\nk.Pa=function(a){try{if(a==this.g)a:{const u=H(this.g);var b=this.g.Ia();const L=this.g.da();if(!(3>u)&&(3!=u||va||this.g&&(this.h.h||this.g.ja()||mc(this.g)))){this.J||4!=u||7==b||(8==b||0>=L?Ob(3):Ob(2));nc(this);var c=this.g.da();this.ca=c;b:if(oc(this)){var d=mc(this.g);a=\"\";var e=d.length,f=4==H(this.g);if(!this.h.i){if(\"undefined\"===typeof TextDecoder){I(this);pc(this);var h=\"\";break b}this.h.i=new l.TextDecoder;}for(b=0;b<e;b++)this.h.h=!0,a+=this.h.i.decode(d[b],{stream:f&&b==e-1});d.splice(0,\ne);this.h.g+=a;this.C=0;h=this.h.g;}else h=this.g.ja();this.i=200==c;Ib(this.j,this.u,this.A,this.m,this.W,u,c);if(this.i){if(this.aa&&!this.K){b:{if(this.g){var n,t=this.g;if((n=t.g?t.g.getResponseHeader(\"X-HTTP-Initial-Response\"):null)&&!x(n)){var m=n;break b}}m=null;}if(c=m)D(this.j,this.m,c,\"Initial handshake response via X-HTTP-Initial-Response\"),this.K=!0,qc(this,c);else {this.i=!1;this.o=3;F(12);I(this);pc(this);break a}}this.S?(rc(this,u,h),va&&this.i&&3==u&&(Db(this.U,this.V,\"tick\",this.mb),\nthis.V.start())):(D(this.j,this.m,h,null),qc(this,h));4==u&&I(this);this.i&&!this.J&&(4==u?sc(this.l,this):(this.i=!1,jc(this)));}else tc(this.g),400==c&&0<h.indexOf(\"Unknown SID\")?(this.o=3,F(12)):(this.o=0,F(13)),I(this),pc(this);}}}catch(u){}finally{}};function oc(a){return a.g?\"GET\"==a.u&&2!=a.L&&a.l.Ha:!1}\nfunction rc(a,b,c){let d=!0,e;for(;!a.J&&a.C<c.length;)if(e=uc(a,c),e==fc){4==b&&(a.o=4,F(14),d=!1);D(a.j,a.m,null,\"[Incomplete Response]\");break}else if(e==ec){a.o=4;F(15);D(a.j,a.m,c,\"[Invalid Chunk]\");d=!1;break}else D(a.j,a.m,e,null),qc(a,e);oc(a)&&e!=fc&&e!=ec&&(a.h.g=\"\",a.C=0);4!=b||0!=c.length||a.h.h||(a.o=1,F(16),d=!1);a.i=a.i&&d;d?0<c.length&&!a.ba&&(a.ba=!0,b=a.l,b.g==a&&b.ca&&!b.M&&(b.l.info(\"Great, no buffering proxy detected. Bytes received: \"+c.length),vc(b),b.M=!0,F(11))):(D(a.j,a.m,\nc,\"[Invalid Chunked Response]\"),I(a),pc(a));}k.mb=function(){if(this.g){var a=H(this.g),b=this.g.ja();this.C<b.length&&(nc(this),rc(this,a,b),this.i&&4!=a&&jc(this));}};function uc(a,b){var c=a.C,d=b.indexOf(\"\\n\",c);if(-1==d)return fc;c=Number(b.substring(c,d));if(isNaN(c))return ec;d+=1;if(d+c>b.length)return fc;b=b.slice(d,d+c);a.C=d+c;return b}k.cancel=function(){this.J=!0;I(this);};function jc(a){a.Y=Date.now()+a.P;wc(a,a.P);}\nfunction wc(a,b){if(null!=a.B)throw Error(\"WatchDog timer not null\");a.B=Rb(q(a.lb,a),b);}function nc(a){a.B&&(l.clearTimeout(a.B),a.B=null);}k.lb=function(){this.B=null;const a=Date.now();0<=a-this.Y?(Kb(this.j,this.A),2!=this.L&&(Ob(),F(17)),I(this),this.o=2,pc(this)):wc(this,this.Y-a);};function pc(a){0==a.l.H||a.J||sc(a.l,a);}function I(a){nc(a);var b=a.M;b&&\"function\"==typeof b.sa&&b.sa();a.M=null;xb(a.V);Fb(a.U);a.g&&(b=a.g,a.g=null,b.abort(),b.sa());}\nfunction qc(a,b){try{var c=a.l;if(0!=c.H&&(c.g==a||xc(c.i,a)))if(!a.K&&xc(c.i,a)&&3==c.H){try{var d=c.Ja.g.parse(b);}catch(m){d=null;}if(Array.isArray(d)&&3==d.length){var e=d;if(0==e[0])a:{if(!c.u){if(c.g)if(c.g.G+3E3<a.G)yc(c),zc(c);else break a;Ac(c);F(18);}}else c.Fa=e[1],0<c.Fa-c.V&&37500>e[2]&&c.G&&0==c.A&&!c.v&&(c.v=Rb(q(c.ib,c),6E3));if(1>=Bc(c.i)&&c.oa){try{c.oa();}catch(m){}c.oa=void 0;}}else J(c,11);}else if((a.K||c.g==a)&&yc(c),!x(b))for(e=c.Ja.g.parse(b),b=0;b<e.length;b++){let m=e[b];c.V=\nm[0];m=m[1];if(2==c.H)if(\"c\"==m[0]){c.K=m[1];c.pa=m[2];const u=m[3];null!=u&&(c.ra=u,c.l.info(\"VER=\"+c.ra));const L=m[4];null!=L&&(c.Ga=L,c.l.info(\"SVER=\"+c.Ga));const La=m[5];null!=La&&\"number\"===typeof La&&0<La&&(d=1.5*La,c.L=d,c.l.info(\"backChannelRequestTimeoutMs_=\"+d));d=c;const la=a.g;if(la){const Ma=la.g?la.g.getResponseHeader(\"X-Client-Wire-Protocol\"):null;if(Ma){var f=d.i;f.g||-1==Ma.indexOf(\"spdy\")&&-1==Ma.indexOf(\"quic\")&&-1==Ma.indexOf(\"h2\")||(f.j=f.l,f.g=new Set,f.h&&(Cc(f,f.h),f.h=null));}if(d.F){const Eb=\nla.g?la.g.getResponseHeader(\"X-HTTP-Session-Id\"):null;Eb&&(d.Da=Eb,K(d.I,d.F,Eb));}}c.H=3;c.h&&c.h.Ba();c.ca&&(c.S=Date.now()-a.G,c.l.info(\"Handshake RTT: \"+c.S+\"ms\"));d=c;var h=a;d.wa=Dc(d,d.J?d.pa:null,d.Y);if(h.K){Ec(d.i,h);var n=h,t=d.L;t&&n.setTimeout(t);n.B&&(nc(n),jc(n));d.g=h;}else Fc(d);0<c.j.length&&Gc(c);}else \"stop\"!=m[0]&&\"close\"!=m[0]||J(c,7);else 3==c.H&&(\"stop\"==m[0]||\"close\"==m[0]?\"stop\"==m[0]?J(c,7):Hc(c):\"noop\"!=m[0]&&c.h&&c.h.Aa(m),c.A=0);}Ob(4);}catch(m){}}function Ic(a){if(a.Z&&\"function\"==typeof a.Z)return a.Z();if(\"undefined\"!==typeof Map&&a instanceof Map||\"undefined\"!==typeof Set&&a instanceof Set)return Array.from(a.values());if(\"string\"===typeof a)return a.split(\"\");if(aa(a)){for(var b=[],c=a.length,d=0;d<c;d++)b.push(a[d]);return b}b=[];c=0;for(d in a)b[c++]=a[d];return b}\nfunction Jc(a){if(a.ta&&\"function\"==typeof a.ta)return a.ta();if(!a.Z||\"function\"!=typeof a.Z){if(\"undefined\"!==typeof Map&&a instanceof Map)return Array.from(a.keys());if(!(\"undefined\"!==typeof Set&&a instanceof Set)){if(aa(a)||\"string\"===typeof a){var b=[];a=a.length;for(var c=0;c<a;c++)b.push(c);return b}b=[];c=0;for(const d in a)b[c++]=d;return b}}}\nfunction Kc(a,b){if(a.forEach&&\"function\"==typeof a.forEach)a.forEach(b,void 0);else if(aa(a)||\"string\"===typeof a)Array.prototype.forEach.call(a,b,void 0);else for(var c=Jc(a),d=Ic(a),e=d.length,f=0;f<e;f++)b.call(void 0,d[f],c&&c[f],a);}var Lc=RegExp(\"^(?:([^:/?#.]+):)?(?://(?:([^\\\\\\\\/?#]*)@)?([^\\\\\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\\\\\/?#]|$))?([^?#]+)?(?:\\\\?([^#]*))?(?:#([\\\\s\\\\S]*))?$\");function Mc(a,b){if(a){a=a.split(\"&\");for(var c=0;c<a.length;c++){var d=a[c].indexOf(\"=\"),e=null;if(0<=d){var f=a[c].substring(0,d);e=a[c].substring(d+1);}else f=a[c];b(f,e?decodeURIComponent(e.replace(/\\+/g,\" \")):\"\");}}}function M(a){this.g=this.s=this.j=\"\";this.m=null;this.o=this.l=\"\";this.h=!1;if(a instanceof M){this.h=a.h;Nc(this,a.j);this.s=a.s;this.g=a.g;Oc(this,a.m);this.l=a.l;var b=a.i;var c=new Pc;c.i=b.i;b.g&&(c.g=new Map(b.g),c.h=b.h);Qc(this,c);this.o=a.o;}else a&&(b=String(a).match(Lc))?(this.h=!1,Nc(this,b[1]||\"\",!0),this.s=Rc(b[2]||\"\"),this.g=Rc(b[3]||\"\",!0),Oc(this,b[4]),this.l=Rc(b[5]||\"\",!0),Qc(this,b[6]||\"\",!0),this.o=Rc(b[7]||\"\")):(this.h=!1,this.i=new Pc(null,this.h));}\nM.prototype.toString=function(){var a=[],b=this.j;b&&a.push(Sc(b,Tc,!0),\":\");var c=this.g;if(c||\"file\"==b)a.push(\"//\"),(b=this.s)&&a.push(Sc(b,Tc,!0),\"@\"),a.push(encodeURIComponent(String(c)).replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),c=this.m,null!=c&&a.push(\":\",String(c));if(c=this.l)this.g&&\"/\"!=c.charAt(0)&&a.push(\"/\"),a.push(Sc(c,\"/\"==c.charAt(0)?Uc:Vc,!0));(c=this.i.toString())&&a.push(\"?\",c);(c=this.o)&&a.push(\"#\",Sc(c,Wc));return a.join(\"\")};function G(a){return new M(a)}\nfunction Nc(a,b,c){a.j=c?Rc(b,!0):b;a.j&&(a.j=a.j.replace(/:$/,\"\"));}function Oc(a,b){if(b){b=Number(b);if(isNaN(b)||0>b)throw Error(\"Bad port number \"+b);a.m=b;}else a.m=null;}function Qc(a,b,c){b instanceof Pc?(a.i=b,Xc(a.i,a.h)):(c||(b=Sc(b,Yc)),a.i=new Pc(b,a.h));}function K(a,b,c){a.i.set(b,c);}function hc(a){K(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36));return a}\nfunction Rc(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}function Sc(a,b,c){return \"string\"===typeof a?(a=encodeURI(a).replace(b,Zc),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Zc(a){a=a.charCodeAt(0);return \"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var Tc=/[#\\/\\?@]/g,Vc=/[#\\?:]/g,Uc=/[#\\?]/g,Yc=/[#\\?@]/g,Wc=/#/g;function Pc(a,b){this.h=this.g=null;this.i=a||null;this.j=!!b;}\nfunction N(a){a.g||(a.g=new Map,a.h=0,a.i&&Mc(a.i,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c);}));}k=Pc.prototype;k.add=function(a,b){N(this);this.i=null;a=O(this,a);var c=this.g.get(a);c||this.g.set(a,c=[]);c.push(b);this.h+=1;return this};function $c(a,b){N(a);b=O(a,b);a.g.has(b)&&(a.i=null,a.h-=a.g.get(b).length,a.g.delete(b));}function ad(a,b){N(a);b=O(a,b);return a.g.has(b)}\nk.forEach=function(a,b){N(this);this.g.forEach(function(c,d){c.forEach(function(e){a.call(b,e,d,this);},this);},this);};k.ta=function(){N(this);const a=Array.from(this.g.values()),b=Array.from(this.g.keys()),c=[];for(let d=0;d<b.length;d++){const e=a[d];for(let f=0;f<e.length;f++)c.push(b[d]);}return c};k.Z=function(a){N(this);let b=[];if(\"string\"===typeof a)ad(this,a)&&(b=b.concat(this.g.get(O(this,a))));else {a=Array.from(this.g.values());for(let c=0;c<a.length;c++)b=b.concat(a[c]);}return b};\nk.set=function(a,b){N(this);this.i=null;a=O(this,a);ad(this,a)&&(this.h-=this.g.get(a).length);this.g.set(a,[b]);this.h+=1;return this};k.get=function(a,b){if(!a)return b;a=this.Z(a);return 0<a.length?String(a[0]):b};function kc(a,b,c){$c(a,b);0<c.length&&(a.i=null,a.g.set(O(a,b),ma(c)),a.h+=c.length);}\nk.toString=function(){if(this.i)return this.i;if(!this.g)return \"\";const a=[],b=Array.from(this.g.keys());for(var c=0;c<b.length;c++){var d=b[c];const f=encodeURIComponent(String(d)),h=this.Z(d);for(d=0;d<h.length;d++){var e=f;\"\"!==h[d]&&(e+=\"=\"+encodeURIComponent(String(h[d])));a.push(e);}}return this.i=a.join(\"&\")};function O(a,b){b=String(b);a.j&&(b=b.toLowerCase());return b}\nfunction Xc(a,b){b&&!a.j&&(N(a),a.i=null,a.g.forEach(function(c,d){var e=d.toLowerCase();d!=e&&($c(this,d),kc(this,e,c));},a));a.j=b;}var bd=class{constructor(a,b){this.g=a;this.map=b;}};function cd(a){this.l=a||dd;l.PerformanceNavigationTiming?(a=l.performance.getEntriesByType(\"navigation\"),a=0<a.length&&(\"hq\"==a[0].nextHopProtocol||\"h2\"==a[0].nextHopProtocol)):a=!!(l.g&&l.g.Ka&&l.g.Ka()&&l.g.Ka().ec);this.j=a?this.l:1;this.g=null;1<this.j&&(this.g=new Set);this.h=null;this.i=[];}var dd=10;function ed(a){return a.h?!0:a.g?a.g.size>=a.j:!1}function Bc(a){return a.h?1:a.g?a.g.size:0}function xc(a,b){return a.h?a.h==b:a.g?a.g.has(b):!1}function Cc(a,b){a.g?a.g.add(b):a.h=b;}\nfunction Ec(a,b){a.h&&a.h==b?a.h=null:a.g&&a.g.has(b)&&a.g.delete(b);}cd.prototype.cancel=function(){this.i=fd(this);if(this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const a of this.g.values())a.cancel();this.g.clear();}};function fd(a){if(null!=a.h)return a.i.concat(a.h.F);if(null!=a.g&&0!==a.g.size){let b=a.i;for(const c of a.g.values())b=b.concat(c.F);return b}return ma(a.i)}var gd=class{stringify(a){return l.JSON.stringify(a,void 0)}parse(a){return l.JSON.parse(a,void 0)}};function hd(){this.g=new gd;}function id(a,b,c){const d=c||\"\";try{Kc(a,function(e,f){let h=e;p(e)&&(h=jb(e));b.push(d+f+\"=\"+encodeURIComponent(h));});}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}}function jd(a,b){const c=new Gb;if(l.Image){const d=new Image;d.onload=ha(kd,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ha(kd,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ha(kd,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ha(kd,c,d,\"TestLoadImage: timeout\",!1,b);l.setTimeout(function(){if(d.ontimeout)d.ontimeout();},1E4);d.src=a;}else b(!1);}function kd(a,b,c,d,e){try{b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d);}catch(f){}}function ld(a){this.l=a.fc||null;this.j=a.ob||!1;}r(ld,Ub);ld.prototype.g=function(){return new md(this.l,this.j)};ld.prototype.i=function(a){return function(){return a}}({});function md(a,b){B.call(this);this.F=a;this.u=b;this.m=void 0;this.readyState=nd;this.status=0;this.responseType=this.responseText=this.response=this.statusText=\"\";this.onreadystatechange=null;this.v=new Headers;this.h=null;this.C=\"GET\";this.B=\"\";this.g=!1;this.A=this.j=this.l=null;}r(md,B);var nd=0;k=md.prototype;\nk.open=function(a,b){if(this.readyState!=nd)throw this.abort(),Error(\"Error reopening a connection\");this.C=a;this.B=b;this.readyState=1;od(this);};k.send=function(a){if(1!=this.readyState)throw this.abort(),Error(\"need to call open() first. \");this.g=!0;const b={headers:this.v,method:this.C,credentials:this.m,cache:void 0};a&&(b.body=a);(this.F||l).fetch(new Request(this.B,b)).then(this.$a.bind(this),this.ka.bind(this));};\nk.abort=function(){this.response=this.responseText=\"\";this.v=new Headers;this.status=0;this.j&&this.j.cancel(\"Request was aborted.\").catch(()=>{});1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,pd(this));this.readyState=nd;};\nk.$a=function(a){if(this.g&&(this.l=a,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=a.headers,this.readyState=2,od(this)),this.g&&(this.readyState=3,od(this),this.g)))if(\"arraybuffer\"===this.responseType)a.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if(\"undefined\"!==typeof l.ReadableStream&&\"body\"in a){this.j=a.body.getReader();if(this.u){if(this.responseType)throw Error('responseType must be empty for \"streamBinaryChunks\" mode responses.');this.response=\n[];}else this.response=this.responseText=\"\",this.A=new TextDecoder;qd(this);}else a.text().then(this.Za.bind(this),this.ka.bind(this));};function qd(a){a.j.read().then(a.Xa.bind(a)).catch(a.ka.bind(a));}k.Xa=function(a){if(this.g){if(this.u&&a.value)this.response.push(a.value);else if(!this.u){var b=a.value?a.value:new Uint8Array(0);if(b=this.A.decode(b,{stream:!a.done}))this.response=this.responseText+=b;}a.done?pd(this):od(this);3==this.readyState&&qd(this);}};\nk.Za=function(a){this.g&&(this.response=this.responseText=a,pd(this));};k.Ya=function(a){this.g&&(this.response=a,pd(this));};k.ka=function(){this.g&&pd(this);};function pd(a){a.readyState=4;a.l=null;a.j=null;a.A=null;od(a);}k.setRequestHeader=function(a,b){this.v.append(a,b);};k.getResponseHeader=function(a){return this.h?this.h.get(a.toLowerCase())||\"\":\"\"};\nk.getAllResponseHeaders=function(){if(!this.h)return \"\";const a=[],b=this.h.entries();for(var c=b.next();!c.done;)c=c.value,a.push(c[0]+\": \"+c[1]),c=b.next();return a.join(\"\\r\\n\")};function od(a){a.onreadystatechange&&a.onreadystatechange.call(a);}Object.defineProperty(md.prototype,\"withCredentials\",{get:function(){return \"include\"===this.m},set:function(a){this.m=a?\"include\":\"same-origin\";}});var rd=l.JSON.parse;function P(a){B.call(this);this.headers=new Map;this.u=a||null;this.h=!1;this.C=this.g=null;this.I=\"\";this.m=0;this.j=\"\";this.l=this.G=this.v=this.F=!1;this.B=0;this.A=null;this.K=sd;this.L=this.M=!1;}r(P,B);var sd=\"\",td=/^https?$/i,ud=[\"POST\",\"PUT\"];k=P.prototype;k.Oa=function(a){this.M=a;};\nk.ha=function(a,b,c,d){if(this.g)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.I+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.I=a;this.j=\"\";this.m=0;this.F=!1;this.h=!0;this.g=this.u?this.u.g():$b.g();this.C=this.u?Vb(this.u):Vb($b);this.g.onreadystatechange=q(this.La,this);try{this.G=!0,this.g.open(b,String(a),!0),this.G=!1;}catch(f){vd(this,f);return}a=c||\"\";c=new Map(this.headers);if(d)if(Object.getPrototypeOf(d)===Object.prototype)for(var e in d)c.set(e,d[e]);else if(\"function\"===\ntypeof d.keys&&\"function\"===typeof d.get)for(const f of d.keys())c.set(f,d.get(f));else throw Error(\"Unknown input type for opt_headers: \"+String(d));d=Array.from(c.keys()).find(f=>\"content-type\"==f.toLowerCase());e=l.FormData&&a instanceof l.FormData;!(0<=ka(ud,b))||d||e||c.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");for(const [f,h]of c)this.g.setRequestHeader(f,h);this.K&&(this.g.responseType=this.K);\"withCredentials\"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=\nthis.M);try{wd(this),0<this.B&&((this.L=xd(this.g))?(this.g.timeout=this.B,this.g.ontimeout=q(this.ua,this)):this.A=yb(this.ua,this.B,this)),this.v=!0,this.g.send(a),this.v=!1;}catch(f){vd(this,f);}};function xd(a){return z&&\"number\"===typeof a.timeout&&void 0!==a.ontimeout}k.ua=function(){\"undefined\"!=typeof goog&&this.g&&(this.j=\"Timed out after \"+this.B+\"ms, aborting\",this.m=8,C(this,\"timeout\"),this.abort(8));};function vd(a,b){a.h=!1;a.g&&(a.l=!0,a.g.abort(),a.l=!1);a.j=b;a.m=5;yd(a);zd(a);}\nfunction yd(a){a.F||(a.F=!0,C(a,\"complete\"),C(a,\"error\"));}k.abort=function(a){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=a||7,C(this,\"complete\"),C(this,\"abort\"),zd(this));};k.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),zd(this,!0));P.$.N.call(this);};k.La=function(){this.s||(this.G||this.v||this.l?Ad(this):this.kb());};k.kb=function(){Ad(this);};\nfunction Ad(a){if(a.h&&\"undefined\"!=typeof goog&&(!a.C[1]||4!=H(a)||2!=a.da()))if(a.v&&4==H(a))yb(a.La,0,a);else if(C(a,\"readystatechange\"),4==H(a)){a.h=!1;try{const h=a.da();a:switch(h){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var b=!0;break a;default:b=!1;}var c;if(!(c=b)){var d;if(d=0===h){var e=String(a.I).match(Lc)[1]||null;!e&&l.self&&l.self.location&&(e=l.self.location.protocol.slice(0,-1));d=!td.test(e?e.toLowerCase():\"\");}c=d;}if(c)C(a,\"complete\"),C(a,\"success\");else {a.m=\n6;try{var f=2<H(a)?a.g.statusText:\"\";}catch(n){f=\"\";}a.j=f+\" [\"+a.da()+\"]\";yd(a);}}finally{zd(a);}}}function zd(a,b){if(a.g){wd(a);const c=a.g,d=a.C[0]?()=>{}:null;a.g=null;a.C=null;b||C(a,\"ready\");try{c.onreadystatechange=d;}catch(e){}}}function wd(a){a.g&&a.L&&(a.g.ontimeout=null);a.A&&(l.clearTimeout(a.A),a.A=null);}k.isActive=function(){return !!this.g};function H(a){return a.g?a.g.readyState:0}k.da=function(){try{return 2<H(this)?this.g.status:-1}catch(a){return -1}};\nk.ja=function(){try{return this.g?this.g.responseText:\"\"}catch(a){return \"\"}};k.Wa=function(a){if(this.g){var b=this.g.responseText;a&&0==b.indexOf(a)&&(b=b.substring(a.length));return rd(b)}};function mc(a){try{if(!a.g)return null;if(\"response\"in a.g)return a.g.response;switch(a.K){case sd:case \"text\":return a.g.responseText;case \"arraybuffer\":if(\"mozResponseArrayBuffer\"in a.g)return a.g.mozResponseArrayBuffer}return null}catch(b){return null}}\nfunction tc(a){const b={};a=(a.g&&2<=H(a)?a.g.getAllResponseHeaders()||\"\":\"\").split(\"\\r\\n\");for(let d=0;d<a.length;d++){if(x(a[d]))continue;var c=qb(a[d]);const e=c[0];c=c[1];if(\"string\"!==typeof c)continue;c=c.trim();const f=b[e]||[];b[e]=f;f.push(c);}Oa(b,function(d){return d.join(\", \")});}k.Ia=function(){return this.m};k.Sa=function(){return \"string\"===typeof this.j?this.j:String(this.j)};function Bd(a){let b=\"\";Na(a,function(c,d){b+=d;b+=\":\";b+=c;b+=\"\\r\\n\";});return b}function Cd(a,b,c){a:{for(d in c){var d=!1;break a}d=!0;}d||(c=Bd(c),\"string\"===typeof a?(null!=c&&encodeURIComponent(String(c))):K(a,b,c));}function Dd(a,b,c){return c&&c.internalChannelParams?c.internalChannelParams[a]||b:b}\nfunction Ed(a){this.Ga=0;this.j=[];this.l=new Gb;this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null;this.fb=this.W=0;this.cb=Dd(\"failFast\",!1,a);this.G=this.v=this.u=this.m=this.h=null;this.aa=!0;this.Fa=this.V=-1;this.ba=this.A=this.C=0;this.ab=Dd(\"baseRetryDelayMs\",5E3,a);this.hb=Dd(\"retryDelaySeedMs\",1E4,a);this.eb=Dd(\"forwardChannelMaxRetries\",2,a);this.xa=Dd(\"forwardChannelRequestTimeoutMs\",2E4,a);this.va=a&&a.xmlHttpFactory||void 0;this.Ha=a&&a.dc||!1;this.L=\nvoid 0;this.J=a&&a.supportsCrossDomainXhr||!1;this.K=\"\";this.i=new cd(a&&a.concurrentRequestLimit);this.Ja=new hd;this.P=a&&a.fastHandshake||!1;this.O=a&&a.encodeInitMessageHeaders||!1;this.P&&this.O&&(this.O=!1);this.bb=a&&a.bc||!1;a&&a.Ea&&this.l.Ea();a&&a.forceLongPolling&&(this.aa=!1);this.ca=!this.P&&this.aa&&a&&a.detectBufferingProxy||!1;this.qa=void 0;a&&a.longPollingTimeout&&0<a.longPollingTimeout&&(this.qa=a.longPollingTimeout);this.oa=void 0;this.S=0;this.M=!1;this.ma=this.B=null;}k=Ed.prototype;\nk.ra=8;k.H=1;function Hc(a){Fd(a);if(3==a.H){var b=a.W++,c=G(a.I);K(c,\"SID\",a.K);K(c,\"RID\",b);K(c,\"TYPE\",\"terminate\");Gd(a,c);b=new bc(a,a.l,b);b.L=2;b.v=hc(G(c));c=!1;if(l.navigator&&l.navigator.sendBeacon)try{c=l.navigator.sendBeacon(b.v.toString(),\"\");}catch(d){}!c&&l.Image&&((new Image).src=b.v,c=!0);c||(b.g=lc(b.l,null),b.g.ha(b.v));b.G=Date.now();jc(b);}Hd(a);}function zc(a){a.g&&(vc(a),a.g.cancel(),a.g=null);}\nfunction Fd(a){zc(a);a.u&&(l.clearTimeout(a.u),a.u=null);yc(a);a.i.cancel();a.m&&(\"number\"===typeof a.m&&l.clearTimeout(a.m),a.m=null);}function Gc(a){if(!ed(a.i)&&!a.m){a.m=!0;var b=a.Na;sb||vb();tb||(sb(),tb=!0);mb.add(b,a);a.C=0;}}function Id(a,b){if(Bc(a.i)>=a.i.j-(a.m?1:0))return !1;if(a.m)return a.j=b.F.concat(a.j),!0;if(1==a.H||2==a.H||a.C>=(a.cb?0:a.eb))return !1;a.m=Rb(q(a.Na,a,b),Jd(a,a.C));a.C++;return !0}\nk.Na=function(a){if(this.m)if(this.m=null,1==this.H){if(!a){this.W=Math.floor(1E5*Math.random());a=this.W++;const e=new bc(this,this.l,a);let f=this.s;this.U&&(f?(f=Pa(f),Ra(f,this.U)):f=this.U);null!==this.o||this.O||(e.I=f,f=null);if(this.P)a:{var b=0;for(var c=0;c<this.j.length;c++){b:{var d=this.j[c];if(\"__data__\"in d.map&&(d=d.map.__data__,\"string\"===typeof d)){d=d.length;break b}d=void 0;}if(void 0===d)break;b+=d;if(4096<b){b=c;break a}if(4096===b||c===this.j.length-1){b=c+1;break a}}b=1E3;}else b=\n1E3;b=Kd(this,e,b);c=G(this.I);K(c,\"RID\",a);K(c,\"CVER\",22);this.F&&K(c,\"X-HTTP-Session-Id\",this.F);Gd(this,c);f&&(this.O?b=\"headers=\"+encodeURIComponent(String(Bd(f)))+\"&\"+b:this.o&&Cd(c,this.o,f));Cc(this.i,e);this.bb&&K(c,\"TYPE\",\"init\");this.P?(K(c,\"$req\",b),K(c,\"SID\",\"null\"),e.aa=!0,gc(e,c,null)):gc(e,c,b);this.H=2;}}else 3==this.H&&(a?Ld(this,a):0==this.j.length||ed(this.i)||Ld(this));};\nfunction Ld(a,b){var c;b?c=b.m:c=a.W++;const d=G(a.I);K(d,\"SID\",a.K);K(d,\"RID\",c);K(d,\"AID\",a.V);Gd(a,d);a.o&&a.s&&Cd(d,a.o,a.s);c=new bc(a,a.l,c,a.C+1);null===a.o&&(c.I=a.s);b&&(a.j=b.F.concat(a.j));b=Kd(a,c,1E3);c.setTimeout(Math.round(.5*a.xa)+Math.round(.5*a.xa*Math.random()));Cc(a.i,c);gc(c,d,b);}function Gd(a,b){a.na&&Na(a.na,function(c,d){K(b,d,c);});a.h&&Kc({},function(c,d){K(b,d,c);});}\nfunction Kd(a,b,c){c=Math.min(a.j.length,c);var d=a.h?q(a.h.Va,a.h,a):null;a:{var e=a.j;let f=-1;for(;;){const h=[\"count=\"+c];-1==f?0<c?(f=e[0].g,h.push(\"ofs=\"+f)):f=0:h.push(\"ofs=\"+f);let n=!0;for(let t=0;t<c;t++){let m=e[t].g;const u=e[t].map;m-=f;if(0>m)f=Math.max(0,e[t].g-100),n=!1;else try{id(u,h,\"req\"+m+\"_\");}catch(L){d&&d(u);}}if(n){d=h.join(\"&\");break a}}}a=a.j.splice(0,c);b.F=a;return d}function Fc(a){if(!a.g&&!a.u){a.ba=1;var b=a.Ma;sb||vb();tb||(sb(),tb=!0);mb.add(b,a);a.A=0;}}\nfunction Ac(a){if(a.g||a.u||3<=a.A)return !1;a.ba++;a.u=Rb(q(a.Ma,a),Jd(a,a.A));a.A++;return !0}k.Ma=function(){this.u=null;Md(this);if(this.ca&&!(this.M||null==this.g||0>=this.S)){var a=2*this.S;this.l.info(\"BP detection timer enabled: \"+a);this.B=Rb(q(this.jb,this),a);}};k.jb=function(){this.B&&(this.B=null,this.l.info(\"BP detection timeout reached.\"),this.l.info(\"Buffering proxy detected and switch to long-polling!\"),this.G=!1,this.M=!0,F(10),zc(this),Md(this));};\nfunction vc(a){null!=a.B&&(l.clearTimeout(a.B),a.B=null);}function Md(a){a.g=new bc(a,a.l,\"rpc\",a.ba);null===a.o&&(a.g.I=a.s);a.g.O=0;var b=G(a.wa);K(b,\"RID\",\"rpc\");K(b,\"SID\",a.K);K(b,\"AID\",a.V);K(b,\"CI\",a.G?\"0\":\"1\");!a.G&&a.qa&&K(b,\"TO\",a.qa);K(b,\"TYPE\",\"xmlhttp\");Gd(a,b);a.o&&a.s&&Cd(b,a.o,a.s);a.L&&a.g.setTimeout(a.L);var c=a.g;a=a.pa;c.L=1;c.v=hc(G(b));c.s=null;c.S=!0;ic(c,a);}k.ib=function(){null!=this.v&&(this.v=null,zc(this),Ac(this),F(19));};\nfunction yc(a){null!=a.v&&(l.clearTimeout(a.v),a.v=null);}function sc(a,b){var c=null;if(a.g==b){yc(a);vc(a);a.g=null;var d=2;}else if(xc(a.i,b))c=b.F,Ec(a.i,b),d=1;else return;if(0!=a.H)if(b.i)if(1==d){c=b.s?b.s.length:0;b=Date.now()-b.G;var e=a.C;d=Mb();C(d,new Qb(d,c));Gc(a);}else Fc(a);else if(e=b.o,3==e||0==e&&0<b.ca||!(1==d&&Id(a,b)||2==d&&Ac(a)))switch(c&&0<c.length&&(b=a.i,b.i=b.i.concat(c)),e){case 1:J(a,5);break;case 4:J(a,10);break;case 3:J(a,6);break;default:J(a,2);}}\nfunction Jd(a,b){let c=a.ab+Math.floor(Math.random()*a.hb);a.isActive()||(c*=2);return c*b}function J(a,b){a.l.info(\"Error code \"+b);if(2==b){var c=null;a.h&&(c=null);var d=q(a.pb,a);c||(c=new M(\"//www.google.com/images/cleardot.gif\"),l.location&&\"http\"==l.location.protocol||Nc(c,\"https\"),hc(c));jd(c.toString(),d);}else F(2);a.H=0;a.h&&a.h.za(b);Hd(a);Fd(a);}k.pb=function(a){a?(this.l.info(\"Successfully pinged google.com\"),F(2)):(this.l.info(\"Failed to ping google.com\"),F(1));};\nfunction Hd(a){a.H=0;a.ma=[];if(a.h){const b=fd(a.i);if(0!=b.length||0!=a.j.length)na(a.ma,b),na(a.ma,a.j),a.i.i.length=0,ma(a.j),a.j.length=0;a.h.ya();}}function Dc(a,b,c){var d=c instanceof M?G(c):new M(c);if(\"\"!=d.g)b&&(d.g=b+\".\"+d.g),Oc(d,d.m);else {var e=l.location;d=e.protocol;b=b?b+\".\"+e.hostname:e.hostname;e=+e.port;var f=new M(null);d&&Nc(f,d);b&&(f.g=b);e&&Oc(f,e);c&&(f.l=c);d=f;}c=a.F;b=a.Da;c&&b&&K(d,c,b);K(d,\"VER\",a.ra);Gd(a,d);return d}\nfunction lc(a,b,c){if(b&&!a.J)throw Error(\"Can't create secondary domain capable XhrIo object.\");b=c&&a.Ha&&!a.va?new P(new ld({ob:!0})):new P(a.va);b.Oa(a.J);return b}k.isActive=function(){return !!this.h&&this.h.isActive(this)};function Nd(){}k=Nd.prototype;k.Ba=function(){};k.Aa=function(){};k.za=function(){};k.ya=function(){};k.isActive=function(){return !0};k.Va=function(){};function Od(){if(z&&!(10<=Number(Fa)))throw Error(\"Environmental error: no available transport.\");}Od.prototype.g=function(a,b){return new Q(a,b)};\nfunction Q(a,b){B.call(this);this.g=new Ed(b);this.l=a;this.h=b&&b.messageUrlParams||null;a=b&&b.messageHeaders||null;b&&b.clientProtocolHeaderRequired&&(a?a[\"X-Client-Protocol\"]=\"webchannel\":a={\"X-Client-Protocol\":\"webchannel\"});this.g.s=a;a=b&&b.initMessageHeaders||null;b&&b.messageContentType&&(a?a[\"X-WebChannel-Content-Type\"]=b.messageContentType:a={\"X-WebChannel-Content-Type\":b.messageContentType});b&&b.Ca&&(a?a[\"X-WebChannel-Client-Profile\"]=b.Ca:a={\"X-WebChannel-Client-Profile\":b.Ca});this.g.U=\na;(a=b&&b.cc)&&!x(a)&&(this.g.o=a);this.A=b&&b.supportsCrossDomainXhr||!1;this.v=b&&b.sendRawJson||!1;(b=b&&b.httpSessionIdParam)&&!x(b)&&(this.g.F=b,a=this.h,null!==a&&b in a&&(a=this.h,b in a&&delete a[b]));this.j=new R(this);}r(Q,B);Q.prototype.m=function(){this.g.h=this.j;this.A&&(this.g.J=!0);var a=this.g,b=this.l,c=this.h||void 0;F(0);a.Y=b;a.na=c||{};a.G=a.aa;a.I=Dc(a,null,a.Y);Gc(a);};Q.prototype.close=function(){Hc(this.g);};\nQ.prototype.u=function(a){var b=this.g;if(\"string\"===typeof a){var c={};c.__data__=a;a=c;}else this.v&&(c={},c.__data__=jb(a),a=c);b.j.push(new bd(b.fb++,a));3==b.H&&Gc(b);};Q.prototype.N=function(){this.g.h=null;delete this.j;Hc(this.g);delete this.g;Q.$.N.call(this);};\nfunction Pd(a){Yb.call(this);a.__headers__&&(this.headers=a.__headers__,this.statusCode=a.__status__,delete a.__headers__,delete a.__status__);var b=a.__sm__;if(b){a:{for(const c in b){a=c;break a}a=void 0;}if(this.i=a)a=this.i,b=null!==b&&a in b?b[a]:void 0;this.data=b;}else this.data=a;}r(Pd,Yb);function Qd(){Zb.call(this);this.status=1;}r(Qd,Zb);function R(a){this.g=a;}r(R,Nd);R.prototype.Ba=function(){C(this.g,\"a\");};R.prototype.Aa=function(a){C(this.g,new Pd(a));};\nR.prototype.za=function(a){C(this.g,new Qd());};R.prototype.ya=function(){C(this.g,\"b\");};function Rd(){this.blockSize=-1;}function S(){this.blockSize=-1;this.blockSize=64;this.g=Array(4);this.m=Array(this.blockSize);this.i=this.h=0;this.reset();}r(S,Rd);S.prototype.reset=function(){this.g[0]=1732584193;this.g[1]=4023233417;this.g[2]=2562383102;this.g[3]=271733878;this.i=this.h=0;};\nfunction Sd(a,b,c){c||(c=0);var d=Array(16);if(\"string\"===typeof b)for(var e=0;16>e;++e)d[e]=b.charCodeAt(c++)|b.charCodeAt(c++)<<8|b.charCodeAt(c++)<<16|b.charCodeAt(c++)<<24;else for(e=0;16>e;++e)d[e]=b[c++]|b[c++]<<8|b[c++]<<16|b[c++]<<24;b=a.g[0];c=a.g[1];e=a.g[2];var f=a.g[3];var h=b+(f^c&(e^f))+d[0]+3614090360&4294967295;b=c+(h<<7&4294967295|h>>>25);h=f+(e^b&(c^e))+d[1]+3905402710&4294967295;f=b+(h<<12&4294967295|h>>>20);h=e+(c^f&(b^c))+d[2]+606105819&4294967295;e=f+(h<<17&4294967295|h>>>15);\nh=c+(b^e&(f^b))+d[3]+3250441966&4294967295;c=e+(h<<22&4294967295|h>>>10);h=b+(f^c&(e^f))+d[4]+4118548399&4294967295;b=c+(h<<7&4294967295|h>>>25);h=f+(e^b&(c^e))+d[5]+1200080426&4294967295;f=b+(h<<12&4294967295|h>>>20);h=e+(c^f&(b^c))+d[6]+2821735955&4294967295;e=f+(h<<17&4294967295|h>>>15);h=c+(b^e&(f^b))+d[7]+4249261313&4294967295;c=e+(h<<22&4294967295|h>>>10);h=b+(f^c&(e^f))+d[8]+1770035416&4294967295;b=c+(h<<7&4294967295|h>>>25);h=f+(e^b&(c^e))+d[9]+2336552879&4294967295;f=b+(h<<12&4294967295|\nh>>>20);h=e+(c^f&(b^c))+d[10]+4294925233&4294967295;e=f+(h<<17&4294967295|h>>>15);h=c+(b^e&(f^b))+d[11]+2304563134&4294967295;c=e+(h<<22&4294967295|h>>>10);h=b+(f^c&(e^f))+d[12]+1804603682&4294967295;b=c+(h<<7&4294967295|h>>>25);h=f+(e^b&(c^e))+d[13]+4254626195&4294967295;f=b+(h<<12&4294967295|h>>>20);h=e+(c^f&(b^c))+d[14]+2792965006&4294967295;e=f+(h<<17&4294967295|h>>>15);h=c+(b^e&(f^b))+d[15]+1236535329&4294967295;c=e+(h<<22&4294967295|h>>>10);h=b+(e^f&(c^e))+d[1]+4129170786&4294967295;b=c+(h<<\n5&4294967295|h>>>27);h=f+(c^e&(b^c))+d[6]+3225465664&4294967295;f=b+(h<<9&4294967295|h>>>23);h=e+(b^c&(f^b))+d[11]+643717713&4294967295;e=f+(h<<14&4294967295|h>>>18);h=c+(f^b&(e^f))+d[0]+3921069994&4294967295;c=e+(h<<20&4294967295|h>>>12);h=b+(e^f&(c^e))+d[5]+3593408605&4294967295;b=c+(h<<5&4294967295|h>>>27);h=f+(c^e&(b^c))+d[10]+38016083&4294967295;f=b+(h<<9&4294967295|h>>>23);h=e+(b^c&(f^b))+d[15]+3634488961&4294967295;e=f+(h<<14&4294967295|h>>>18);h=c+(f^b&(e^f))+d[4]+3889429448&4294967295;c=\ne+(h<<20&4294967295|h>>>12);h=b+(e^f&(c^e))+d[9]+568446438&4294967295;b=c+(h<<5&4294967295|h>>>27);h=f+(c^e&(b^c))+d[14]+3275163606&4294967295;f=b+(h<<9&4294967295|h>>>23);h=e+(b^c&(f^b))+d[3]+4107603335&4294967295;e=f+(h<<14&4294967295|h>>>18);h=c+(f^b&(e^f))+d[8]+1163531501&4294967295;c=e+(h<<20&4294967295|h>>>12);h=b+(e^f&(c^e))+d[13]+2850285829&4294967295;b=c+(h<<5&4294967295|h>>>27);h=f+(c^e&(b^c))+d[2]+4243563512&4294967295;f=b+(h<<9&4294967295|h>>>23);h=e+(b^c&(f^b))+d[7]+1735328473&4294967295;\ne=f+(h<<14&4294967295|h>>>18);h=c+(f^b&(e^f))+d[12]+2368359562&4294967295;c=e+(h<<20&4294967295|h>>>12);h=b+(c^e^f)+d[5]+4294588738&4294967295;b=c+(h<<4&4294967295|h>>>28);h=f+(b^c^e)+d[8]+2272392833&4294967295;f=b+(h<<11&4294967295|h>>>21);h=e+(f^b^c)+d[11]+1839030562&4294967295;e=f+(h<<16&4294967295|h>>>16);h=c+(e^f^b)+d[14]+4259657740&4294967295;c=e+(h<<23&4294967295|h>>>9);h=b+(c^e^f)+d[1]+2763975236&4294967295;b=c+(h<<4&4294967295|h>>>28);h=f+(b^c^e)+d[4]+1272893353&4294967295;f=b+(h<<11&4294967295|\nh>>>21);h=e+(f^b^c)+d[7]+4139469664&4294967295;e=f+(h<<16&4294967295|h>>>16);h=c+(e^f^b)+d[10]+3200236656&4294967295;c=e+(h<<23&4294967295|h>>>9);h=b+(c^e^f)+d[13]+681279174&4294967295;b=c+(h<<4&4294967295|h>>>28);h=f+(b^c^e)+d[0]+3936430074&4294967295;f=b+(h<<11&4294967295|h>>>21);h=e+(f^b^c)+d[3]+3572445317&4294967295;e=f+(h<<16&4294967295|h>>>16);h=c+(e^f^b)+d[6]+76029189&4294967295;c=e+(h<<23&4294967295|h>>>9);h=b+(c^e^f)+d[9]+3654602809&4294967295;b=c+(h<<4&4294967295|h>>>28);h=f+(b^c^e)+d[12]+\n3873151461&4294967295;f=b+(h<<11&4294967295|h>>>21);h=e+(f^b^c)+d[15]+530742520&4294967295;e=f+(h<<16&4294967295|h>>>16);h=c+(e^f^b)+d[2]+3299628645&4294967295;c=e+(h<<23&4294967295|h>>>9);h=b+(e^(c|~f))+d[0]+4096336452&4294967295;b=c+(h<<6&4294967295|h>>>26);h=f+(c^(b|~e))+d[7]+1126891415&4294967295;f=b+(h<<10&4294967295|h>>>22);h=e+(b^(f|~c))+d[14]+2878612391&4294967295;e=f+(h<<15&4294967295|h>>>17);h=c+(f^(e|~b))+d[5]+4237533241&4294967295;c=e+(h<<21&4294967295|h>>>11);h=b+(e^(c|~f))+d[12]+1700485571&\n4294967295;b=c+(h<<6&4294967295|h>>>26);h=f+(c^(b|~e))+d[3]+2399980690&4294967295;f=b+(h<<10&4294967295|h>>>22);h=e+(b^(f|~c))+d[10]+4293915773&4294967295;e=f+(h<<15&4294967295|h>>>17);h=c+(f^(e|~b))+d[1]+2240044497&4294967295;c=e+(h<<21&4294967295|h>>>11);h=b+(e^(c|~f))+d[8]+1873313359&4294967295;b=c+(h<<6&4294967295|h>>>26);h=f+(c^(b|~e))+d[15]+4264355552&4294967295;f=b+(h<<10&4294967295|h>>>22);h=e+(b^(f|~c))+d[6]+2734768916&4294967295;e=f+(h<<15&4294967295|h>>>17);h=c+(f^(e|~b))+d[13]+1309151649&\n4294967295;c=e+(h<<21&4294967295|h>>>11);h=b+(e^(c|~f))+d[4]+4149444226&4294967295;b=c+(h<<6&4294967295|h>>>26);h=f+(c^(b|~e))+d[11]+3174756917&4294967295;f=b+(h<<10&4294967295|h>>>22);h=e+(b^(f|~c))+d[2]+718787259&4294967295;e=f+(h<<15&4294967295|h>>>17);h=c+(f^(e|~b))+d[9]+3951481745&4294967295;a.g[0]=a.g[0]+b&4294967295;a.g[1]=a.g[1]+(e+(h<<21&4294967295|h>>>11))&4294967295;a.g[2]=a.g[2]+e&4294967295;a.g[3]=a.g[3]+f&4294967295;}\nS.prototype.j=function(a,b){void 0===b&&(b=a.length);for(var c=b-this.blockSize,d=this.m,e=this.h,f=0;f<b;){if(0==e)for(;f<=c;)Sd(this,a,f),f+=this.blockSize;if(\"string\"===typeof a)for(;f<b;){if(d[e++]=a.charCodeAt(f++),e==this.blockSize){Sd(this,d);e=0;break}}else for(;f<b;)if(d[e++]=a[f++],e==this.blockSize){Sd(this,d);e=0;break}}this.h=e;this.i+=b;};\nS.prototype.l=function(){var a=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);a[0]=128;for(var b=1;b<a.length-8;++b)a[b]=0;var c=8*this.i;for(b=a.length-8;b<a.length;++b)a[b]=c&255,c/=256;this.j(a);a=Array(16);for(b=c=0;4>b;++b)for(var d=0;32>d;d+=8)a[c++]=this.g[b]>>>d&255;return a};function T(a,b){this.h=b;for(var c=[],d=!0,e=a.length-1;0<=e;e--){var f=a[e]|0;d&&f==b||(c[e]=f,d=!1);}this.g=c;}var sa={};function Td(a){return -128<=a&&128>a?ra(a,function(b){return new T([b|0],0>b?-1:0)}):new T([a|0],0>a?-1:0)}function U(a){if(isNaN(a)||!isFinite(a))return V;if(0>a)return W(U(-a));for(var b=[],c=1,d=0;a>=c;d++)b[d]=a/c|0,c*=Ud;return new T(b,0)}\nfunction Vd(a,b){if(0==a.length)throw Error(\"number format error: empty string\");b=b||10;if(2>b||36<b)throw Error(\"radix out of range: \"+b);if(\"-\"==a.charAt(0))return W(Vd(a.substring(1),b));if(0<=a.indexOf(\"-\"))throw Error('number format error: interior \"-\" character');for(var c=U(Math.pow(b,8)),d=V,e=0;e<a.length;e+=8){var f=Math.min(8,a.length-e),h=parseInt(a.substring(e,e+f),b);8>f?(f=U(Math.pow(b,f)),d=d.R(f).add(U(h))):(d=d.R(c),d=d.add(U(h)));}return d}\nvar Ud=4294967296,V=Td(0),Wd=Td(1),Xd=Td(16777216);k=T.prototype;k.ea=function(){if(X(this))return -W(this).ea();for(var a=0,b=1,c=0;c<this.g.length;c++){var d=this.D(c);a+=(0<=d?d:Ud+d)*b;b*=Ud;}return a};\nk.toString=function(a){a=a||10;if(2>a||36<a)throw Error(\"radix out of range: \"+a);if(Y(this))return \"0\";if(X(this))return \"-\"+W(this).toString(a);for(var b=U(Math.pow(a,6)),c=this,d=\"\";;){var e=Yd(c,b).g;c=Zd(c,e.R(b));var f=((0<c.g.length?c.g[0]:c.h)>>>0).toString(a);c=e;if(Y(c))return f+d;for(;6>f.length;)f=\"0\"+f;d=f+d;}};k.D=function(a){return 0>a?0:a<this.g.length?this.g[a]:this.h};function Y(a){if(0!=a.h)return !1;for(var b=0;b<a.g.length;b++)if(0!=a.g[b])return !1;return !0}\nfunction X(a){return -1==a.h}k.X=function(a){a=Zd(this,a);return X(a)?-1:Y(a)?0:1};function W(a){for(var b=a.g.length,c=[],d=0;d<b;d++)c[d]=~a.g[d];return (new T(c,~a.h)).add(Wd)}k.abs=function(){return X(this)?W(this):this};k.add=function(a){for(var b=Math.max(this.g.length,a.g.length),c=[],d=0,e=0;e<=b;e++){var f=d+(this.D(e)&65535)+(a.D(e)&65535),h=(f>>>16)+(this.D(e)>>>16)+(a.D(e)>>>16);d=h>>>16;f&=65535;h&=65535;c[e]=h<<16|f;}return new T(c,c[c.length-1]&-2147483648?-1:0)};\nfunction Zd(a,b){return a.add(W(b))}\nk.R=function(a){if(Y(this)||Y(a))return V;if(X(this))return X(a)?W(this).R(W(a)):W(W(this).R(a));if(X(a))return W(this.R(W(a)));if(0>this.X(Xd)&&0>a.X(Xd))return U(this.ea()*a.ea());for(var b=this.g.length+a.g.length,c=[],d=0;d<2*b;d++)c[d]=0;for(d=0;d<this.g.length;d++)for(var e=0;e<a.g.length;e++){var f=this.D(d)>>>16,h=this.D(d)&65535,n=a.D(e)>>>16,t=a.D(e)&65535;c[2*d+2*e]+=h*t;$d(c,2*d+2*e);c[2*d+2*e+1]+=f*t;$d(c,2*d+2*e+1);c[2*d+2*e+1]+=h*n;$d(c,2*d+2*e+1);c[2*d+2*e+2]+=f*n;$d(c,2*d+2*e+2);}for(d=\n0;d<b;d++)c[d]=c[2*d+1]<<16|c[2*d];for(d=b;d<2*b;d++)c[d]=0;return new T(c,0)};function $d(a,b){for(;(a[b]&65535)!=a[b];)a[b+1]+=a[b]>>>16,a[b]&=65535,b++;}function ae(a,b){this.g=a;this.h=b;}\nfunction Yd(a,b){if(Y(b))throw Error(\"division by zero\");if(Y(a))return new ae(V,V);if(X(a))return b=Yd(W(a),b),new ae(W(b.g),W(b.h));if(X(b))return b=Yd(a,W(b)),new ae(W(b.g),b.h);if(30<a.g.length){if(X(a)||X(b))throw Error(\"slowDivide_ only works with positive integers.\");for(var c=Wd,d=b;0>=d.X(a);)c=be(c),d=be(d);var e=Z(c,1),f=Z(d,1);d=Z(d,2);for(c=Z(c,2);!Y(d);){var h=f.add(d);0>=h.X(a)&&(e=e.add(c),f=h);d=Z(d,1);c=Z(c,1);}b=Zd(a,e.R(b));return new ae(e,b)}for(e=V;0<=a.X(b);){c=Math.max(1,Math.floor(a.ea()/\nb.ea()));d=Math.ceil(Math.log(c)/Math.LN2);d=48>=d?1:Math.pow(2,d-48);f=U(c);for(h=f.R(b);X(h)||0<h.X(a);)c-=d,f=U(c),h=f.R(b);Y(f)&&(f=Wd);e=e.add(f);a=Zd(a,h);}return new ae(e,a)}k.gb=function(a){return Yd(this,a).h};k.and=function(a){for(var b=Math.max(this.g.length,a.g.length),c=[],d=0;d<b;d++)c[d]=this.D(d)&a.D(d);return new T(c,this.h&a.h)};k.or=function(a){for(var b=Math.max(this.g.length,a.g.length),c=[],d=0;d<b;d++)c[d]=this.D(d)|a.D(d);return new T(c,this.h|a.h)};\nk.xor=function(a){for(var b=Math.max(this.g.length,a.g.length),c=[],d=0;d<b;d++)c[d]=this.D(d)^a.D(d);return new T(c,this.h^a.h)};function be(a){for(var b=a.g.length+1,c=[],d=0;d<b;d++)c[d]=a.D(d)<<1|a.D(d-1)>>>31;return new T(c,a.h)}function Z(a,b){var c=b>>5;b%=32;for(var d=a.g.length-c,e=[],f=0;f<d;f++)e[f]=0<b?a.D(f+c)>>>b|a.D(f+c+1)<<32-b:a.D(f+c);return new T(e,a.h)}Od.prototype.createWebChannel=Od.prototype.g;Q.prototype.send=Q.prototype.u;Q.prototype.open=Q.prototype.m;Q.prototype.close=Q.prototype.close;Sb.NO_ERROR=0;Sb.TIMEOUT=8;Sb.HTTP_ERROR=6;Tb.COMPLETE=\"complete\";Wb.EventType=Xb;Xb.OPEN=\"a\";Xb.CLOSE=\"b\";Xb.ERROR=\"c\";Xb.MESSAGE=\"d\";B.prototype.listen=B.prototype.O;P.prototype.listenOnce=P.prototype.P;P.prototype.getLastError=P.prototype.Sa;P.prototype.getLastErrorCode=P.prototype.Ia;P.prototype.getStatus=P.prototype.da;P.prototype.getResponseJson=P.prototype.Wa;\nP.prototype.getResponseText=P.prototype.ja;P.prototype.send=P.prototype.ha;P.prototype.setWithCredentials=P.prototype.Oa;S.prototype.digest=S.prototype.l;S.prototype.reset=S.prototype.reset;S.prototype.update=S.prototype.j;T.prototype.add=T.prototype.add;T.prototype.multiply=T.prototype.R;T.prototype.modulo=T.prototype.gb;T.prototype.compare=T.prototype.X;T.prototype.toNumber=T.prototype.ea;T.prototype.toString=T.prototype.toString;T.prototype.getBits=T.prototype.D;T.fromNumber=U;T.fromString=Vd;\nvar createWebChannelTransport = esm.createWebChannelTransport=function(){return new Od};var getStatEventTarget = esm.getStatEventTarget=function(){return Mb()};var ErrorCode = esm.ErrorCode=Sb;var EventType = esm.EventType=Tb;var Event = esm.Event=E;var Stat = esm.Stat={xb:0,Ab:1,Bb:2,Ub:3,Zb:4,Wb:5,Xb:6,Vb:7,Tb:8,Yb:9,PROXY:10,NOPROXY:11,Rb:12,Nb:13,Ob:14,Mb:15,Pb:16,Qb:17,tb:18,sb:19,ub:20};var FetchXmlHttpFactory = esm.FetchXmlHttpFactory=ld;var WebChannel = esm.WebChannel=Wb;var XhrIo = esm.XhrIo=P;var Md5 = esm.Md5=S;var Integer = esm.Integer=T;\n\nexport { ErrorCode, Event, EventType, FetchXmlHttpFactory, Integer, Md5, Stat, WebChannel, XhrIo, createWebChannelTransport, esm as default, getStatEventTarget };\n//# sourceMappingURL=index.esm2017.js.map\n","import { _registerComponent, registerVersion, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { FirebaseError, createMockUserToken, getModularInstance, deepEqual, getDefaultEmulatorHostnameAndPort, getUA, isIndexedDBAvailable, isSafari } from '@firebase/util';\nimport { Integer, XhrIo, EventType, ErrorCode, createWebChannelTransport, getStatEventTarget, FetchXmlHttpFactory, WebChannel, Event, Stat, Md5 } from '@firebase/webchannel-wrapper';\n\nconst S = \"@firebase/firestore\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nclass User {\n    constructor(e) {\n        this.uid = e;\n    }\n    isAuthenticated() {\n        return null != this.uid;\n    }\n    /**\n     * Returns a key representing this user, suitable for inclusion in a\n     * dictionary.\n     */    toKey() {\n        return this.isAuthenticated() ? \"uid:\" + this.uid : \"anonymous-user\";\n    }\n    isEqual(e) {\n        return e.uid === this.uid;\n    }\n}\n\n/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), \n// TODO(mikelehen): Look into getting a proper uid-equivalent for\n// non-FirebaseAuth providers.\nUser.GOOGLE_CREDENTIALS = new User(\"google-credentials-uid\"), User.FIRST_PARTY = new User(\"first-party-uid\"), \nUser.MOCK_USER = new User(\"mock-user\");\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet b = \"10.1.0\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst D = new Logger(\"@firebase/firestore\");\n\n// Helper methods are needed because variables can't be exported as read/write\nfunction __PRIVATE_getLogLevel() {\n    return D.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n *   be any of the following values:\n *\n *   <ul>\n *     <li>`debug` for the most verbose logging level, primarily for\n *     debugging.</li>\n *     <li>`error` to log errors only.</li>\n *     <li><code>`silent` to turn off logging.</li>\n *   </ul>\n */ function setLogLevel(e) {\n    D.setLogLevel(e);\n}\n\nfunction __PRIVATE_logDebug(e, ...t) {\n    if (D.logLevel <= LogLevel.DEBUG) {\n        const n = t.map(__PRIVATE_argToString);\n        D.debug(`Firestore (${b}): ${e}`, ...n);\n    }\n}\n\nfunction __PRIVATE_logError(e, ...t) {\n    if (D.logLevel <= LogLevel.ERROR) {\n        const n = t.map(__PRIVATE_argToString);\n        D.error(`Firestore (${b}): ${e}`, ...n);\n    }\n}\n\n/**\n * @internal\n */ function __PRIVATE_logWarn(e, ...t) {\n    if (D.logLevel <= LogLevel.WARN) {\n        const n = t.map(__PRIVATE_argToString);\n        D.warn(`Firestore (${b}): ${e}`, ...n);\n    }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */ function __PRIVATE_argToString(e) {\n    if (\"string\" == typeof e) return e;\n    try {\n        /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n        /** Formats an object as a JSON string, suitable for logging. */\n        return function __PRIVATE_formatJSON(e) {\n            return JSON.stringify(e);\n        }(e);\n    } catch (t) {\n        // Converting to JSON failed, just log the object directly\n        return e;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */ function fail(e = \"Unexpected state\") {\n    // Log the failure in addition to throw an exception, just in case the\n    // exception is swallowed.\n    const t = `FIRESTORE (${b}) INTERNAL ASSERTION FAILED: ` + e;\n    // NOTE: We don't use FirestoreError here because these are internal failures\n    // that cannot be handled by the user. (Also it would create a circular\n    // dependency between the error and assert modules which doesn't work.)\n    throw __PRIVATE_logError(t), new Error(t);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */ function __PRIVATE_hardAssert(e, t) {\n    e || fail();\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */ function __PRIVATE_debugAssert(e, t) {\n    e || fail();\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */ function __PRIVATE_debugCast(e, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nt) {\n    return e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const v = {\n    // Causes are copied from:\n    // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n    /** Not an error; returned on success. */\n    OK: \"ok\",\n    /** The operation was cancelled (typically by the caller). */\n    CANCELLED: \"cancelled\",\n    /** Unknown error or an error from a different error domain. */\n    UNKNOWN: \"unknown\",\n    /**\n     * Client specified an invalid argument. Note that this differs from\n     * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n     * problematic regardless of the state of the system (e.g., a malformed file\n     * name).\n     */\n    INVALID_ARGUMENT: \"invalid-argument\",\n    /**\n     * Deadline expired before operation could complete. For operations that\n     * change the state of the system, this error may be returned even if the\n     * operation has completed successfully. For example, a successful response\n     * from a server could have been delayed long enough for the deadline to\n     * expire.\n     */\n    DEADLINE_EXCEEDED: \"deadline-exceeded\",\n    /** Some requested entity (e.g., file or directory) was not found. */\n    NOT_FOUND: \"not-found\",\n    /**\n     * Some entity that we attempted to create (e.g., file or directory) already\n     * exists.\n     */\n    ALREADY_EXISTS: \"already-exists\",\n    /**\n     * The caller does not have permission to execute the specified operation.\n     * PERMISSION_DENIED must not be used for rejections caused by exhausting\n     * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n     * PERMISSION_DENIED must not be used if the caller can not be identified\n     * (use UNAUTHENTICATED instead for those errors).\n     */\n    PERMISSION_DENIED: \"permission-denied\",\n    /**\n     * The request does not have valid authentication credentials for the\n     * operation.\n     */\n    UNAUTHENTICATED: \"unauthenticated\",\n    /**\n     * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n     * entire file system is out of space.\n     */\n    RESOURCE_EXHAUSTED: \"resource-exhausted\",\n    /**\n     * Operation was rejected because the system is not in a state required for\n     * the operation's execution. For example, directory to be deleted may be\n     * non-empty, an rmdir operation is applied to a non-directory, etc.\n     *\n     * A litmus test that may help a service implementor in deciding\n     * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n     *  (a) Use UNAVAILABLE if the client can retry just the failing call.\n     *  (b) Use ABORTED if the client should retry at a higher-level\n     *      (e.g., restarting a read-modify-write sequence).\n     *  (c) Use FAILED_PRECONDITION if the client should not retry until\n     *      the system state has been explicitly fixed. E.g., if an \"rmdir\"\n     *      fails because the directory is non-empty, FAILED_PRECONDITION\n     *      should be returned since the client should not retry unless\n     *      they have first fixed up the directory by deleting files from it.\n     *  (d) Use FAILED_PRECONDITION if the client performs conditional\n     *      REST Get/Update/Delete on a resource and the resource on the\n     *      server does not match the condition. E.g., conflicting\n     *      read-modify-write on the same resource.\n     */\n    FAILED_PRECONDITION: \"failed-precondition\",\n    /**\n     * The operation was aborted, typically due to a concurrency issue like\n     * sequencer check failures, transaction aborts, etc.\n     *\n     * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n     * and UNAVAILABLE.\n     */\n    ABORTED: \"aborted\",\n    /**\n     * Operation was attempted past the valid range. E.g., seeking or reading\n     * past end of file.\n     *\n     * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n     * if the system state changes. For example, a 32-bit file system will\n     * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n     * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n     * an offset past the current file size.\n     *\n     * There is a fair bit of overlap between FAILED_PRECONDITION and\n     * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n     * when it applies so that callers who are iterating through a space can\n     * easily look for an OUT_OF_RANGE error to detect when they are done.\n     */\n    OUT_OF_RANGE: \"out-of-range\",\n    /** Operation is not implemented or not supported/enabled in this service. */\n    UNIMPLEMENTED: \"unimplemented\",\n    /**\n     * Internal errors. Means some invariants expected by underlying System has\n     * been broken. If you see one of these errors, Something is very broken.\n     */\n    INTERNAL: \"internal\",\n    /**\n     * The service is currently unavailable. This is a most likely a transient\n     * condition and may be corrected by retrying with a backoff.\n     *\n     * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n     * and UNAVAILABLE.\n     */\n    UNAVAILABLE: \"unavailable\",\n    /** Unrecoverable data loss or corruption. */\n    DATA_LOSS: \"data-loss\"\n};\n\n/** An error returned by a Firestore operation. */ class FirestoreError extends FirebaseError {\n    /** @hideconstructor */\n    constructor(\n    /**\n     * The backend error code associated with this error.\n     */\n    e, \n    /**\n     * A custom error description.\n     */\n    t) {\n        super(e, t), this.code = e, this.message = t, \n        // HACK: We write a toString property directly because Error is not a real\n        // class and so inheritance does not work correctly. We could alternatively\n        // do the same \"back-door inheritance\" trick that FirebaseError does.\n        this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_Deferred {\n    constructor() {\n        this.promise = new Promise(((e, t) => {\n            this.resolve = e, this.reject = t;\n        }));\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_OAuthToken {\n    constructor(e, t) {\n        this.user = t, this.type = \"OAuth\", this.headers = new Map, this.headers.set(\"Authorization\", `Bearer ${e}`);\n    }\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */ class __PRIVATE_EmptyAuthCredentialsProvider {\n    getToken() {\n        return Promise.resolve(null);\n    }\n    invalidateToken() {}\n    start(e, t) {\n        // Fire with initial user.\n        e.enqueueRetryable((() => t(User.UNAUTHENTICATED)));\n    }\n    shutdown() {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */ class __PRIVATE_EmulatorAuthCredentialsProvider {\n    constructor(e) {\n        this.token = e, \n        /**\n         * Stores the listener registered with setChangeListener()\n         * This isn't actually necessary since the UID never changes, but we use this\n         * to verify the listen contract is adhered to in tests.\n         */\n        this.changeListener = null;\n    }\n    getToken() {\n        return Promise.resolve(this.token);\n    }\n    invalidateToken() {}\n    start(e, t) {\n        this.changeListener = t, \n        // Fire with initial user.\n        e.enqueueRetryable((() => t(this.token.user)));\n    }\n    shutdown() {\n        this.changeListener = null;\n    }\n}\n\nclass __PRIVATE_FirebaseAuthCredentialsProvider {\n    constructor(e) {\n        this.t = e, \n        /** Tracks the current User. */\n        this.currentUser = User.UNAUTHENTICATED, \n        /**\n         * Counter used to detect if the token changed while a getToken request was\n         * outstanding.\n         */\n        this.i = 0, this.forceRefresh = !1, this.auth = null;\n    }\n    start(e, t) {\n        let n = this.i;\n        // A change listener that prevents double-firing for the same token change.\n                const __PRIVATE_guardedChangeListener = e => this.i !== n ? (n = this.i, \n        t(e)) : Promise.resolve();\n        // A promise that can be waited on to block on the next token change.\n        // This promise is re-created after each change.\n                let r = new __PRIVATE_Deferred;\n        this.o = () => {\n            this.i++, this.currentUser = this.u(), r.resolve(), r = new __PRIVATE_Deferred, \n            e.enqueueRetryable((() => __PRIVATE_guardedChangeListener(this.currentUser)));\n        };\n        const __PRIVATE_awaitNextToken = () => {\n            const t = r;\n            e.enqueueRetryable((async () => {\n                await t.promise, await __PRIVATE_guardedChangeListener(this.currentUser);\n            }));\n        }, __PRIVATE_registerAuth = e => {\n            __PRIVATE_logDebug(\"FirebaseAuthCredentialsProvider\", \"Auth detected\"), this.auth = e, \n            this.auth.addAuthTokenListener(this.o), __PRIVATE_awaitNextToken();\n        };\n        this.t.onInit((e => __PRIVATE_registerAuth(e))), \n        // Our users can initialize Auth right after Firestore, so we give it\n        // a chance to register itself with the component framework before we\n        // determine whether to start up in unauthenticated mode.\n        setTimeout((() => {\n            if (!this.auth) {\n                const e = this.t.getImmediate({\n                    optional: !0\n                });\n                e ? __PRIVATE_registerAuth(e) : (\n                // If auth is still not available, proceed with `null` user\n                __PRIVATE_logDebug(\"FirebaseAuthCredentialsProvider\", \"Auth not yet detected\"), \n                r.resolve(), r = new __PRIVATE_Deferred);\n            }\n        }), 0), __PRIVATE_awaitNextToken();\n    }\n    getToken() {\n        // Take note of the current value of the tokenCounter so that this method\n        // can fail (with an ABORTED error) if there is a token change while the\n        // request is outstanding.\n        const e = this.i, t = this.forceRefresh;\n        return this.forceRefresh = !1, this.auth ? this.auth.getToken(t).then((t => \n        // Cancel the request since the token changed while the request was\n        // outstanding so the response is potentially for a previous user (which\n        // user, we can't be sure).\n        this.i !== e ? (__PRIVATE_logDebug(\"FirebaseAuthCredentialsProvider\", \"getToken aborted due to token change.\"), \n        this.getToken()) : t ? (__PRIVATE_hardAssert(\"string\" == typeof t.accessToken), \n        new __PRIVATE_OAuthToken(t.accessToken, this.currentUser)) : null)) : Promise.resolve(null);\n    }\n    invalidateToken() {\n        this.forceRefresh = !0;\n    }\n    shutdown() {\n        this.auth && this.auth.removeAuthTokenListener(this.o);\n    }\n    // Auth.getUid() can return null even with a user logged in. It is because\n    // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n    // This method should only be called in the AuthTokenListener callback\n    // to guarantee to get the actual user.\n    u() {\n        const e = this.auth && this.auth.getUid();\n        return __PRIVATE_hardAssert(null === e || \"string\" == typeof e), new User(e);\n    }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */ class __PRIVATE_FirstPartyToken {\n    constructor(e, t, n) {\n        this.l = e, this.h = t, this.P = n, this.type = \"FirstParty\", this.user = User.FIRST_PARTY, \n        this.I = new Map;\n    }\n    /**\n     * Gets an authorization token, using a provided factory function, or return\n     * null.\n     */    T() {\n        return this.P ? this.P() : null;\n    }\n    get headers() {\n        this.I.set(\"X-Goog-AuthUser\", this.l);\n        // Use array notation to prevent minification\n        const e = this.T();\n        return e && this.I.set(\"Authorization\", e), this.h && this.I.set(\"X-Goog-Iam-Authorization-Token\", this.h), \n        this.I;\n    }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */ class __PRIVATE_FirstPartyAuthCredentialsProvider {\n    constructor(e, t, n) {\n        this.l = e, this.h = t, this.P = n;\n    }\n    getToken() {\n        return Promise.resolve(new __PRIVATE_FirstPartyToken(this.l, this.h, this.P));\n    }\n    start(e, t) {\n        // Fire with initial uid.\n        e.enqueueRetryable((() => t(User.FIRST_PARTY)));\n    }\n    shutdown() {}\n    invalidateToken() {}\n}\n\nclass AppCheckToken {\n    constructor(e) {\n        this.value = e, this.type = \"AppCheck\", this.headers = new Map, e && e.length > 0 && this.headers.set(\"x-firebase-appcheck\", this.value);\n    }\n}\n\nclass __PRIVATE_FirebaseAppCheckTokenProvider {\n    constructor(e) {\n        this.A = e, this.forceRefresh = !1, this.appCheck = null, this.R = null;\n    }\n    start(e, t) {\n        const onTokenChanged = e => {\n            null != e.error && __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", `Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);\n            const n = e.token !== this.R;\n            return this.R = e.token, __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", `Received ${n ? \"new\" : \"existing\"} token.`), \n            n ? t(e.token) : Promise.resolve();\n        };\n        this.o = t => {\n            e.enqueueRetryable((() => onTokenChanged(t)));\n        };\n        const __PRIVATE_registerAppCheck = e => {\n            __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", \"AppCheck detected\"), this.appCheck = e, \n            this.appCheck.addTokenListener(this.o);\n        };\n        this.A.onInit((e => __PRIVATE_registerAppCheck(e))), \n        // Our users can initialize AppCheck after Firestore, so we give it\n        // a chance to register itself with the component framework.\n        setTimeout((() => {\n            if (!this.appCheck) {\n                const e = this.A.getImmediate({\n                    optional: !0\n                });\n                e ? __PRIVATE_registerAppCheck(e) : \n                // If AppCheck is still not available, proceed without it.\n                __PRIVATE_logDebug(\"FirebaseAppCheckTokenProvider\", \"AppCheck not yet detected\");\n            }\n        }), 0);\n    }\n    getToken() {\n        const e = this.forceRefresh;\n        return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(e).then((e => e ? (__PRIVATE_hardAssert(\"string\" == typeof e.token), \n        this.R = e.token, new AppCheckToken(e.token)) : null)) : Promise.resolve(null);\n    }\n    invalidateToken() {\n        this.forceRefresh = !0;\n    }\n    shutdown() {\n        this.appCheck && this.appCheck.removeTokenListener(this.o);\n    }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */ class __PRIVATE_EmptyAppCheckTokenProvider {\n    getToken() {\n        return Promise.resolve(new AppCheckToken(\"\"));\n    }\n    invalidateToken() {}\n    start(e, t) {}\n    shutdown() {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nfunction __PRIVATE_randomBytes(e) {\n    // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n    const t = \n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    \"undefined\" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(e);\n    if (t && \"function\" == typeof t.getRandomValues) t.getRandomValues(n); else \n    // Falls back to Math.random\n    for (let t = 0; t < e; t++) n[t] = Math.floor(256 * Math.random());\n    return n;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_AutoId {\n    static V() {\n        // Alphanumeric characters\n        const e = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", t = Math.floor(256 / e.length) * e.length;\n        // The largest byte value that is a multiple of `char.length`.\n                let n = \"\";\n        for (;n.length < 20; ) {\n            const r = __PRIVATE_randomBytes(40);\n            for (let i = 0; i < r.length; ++i) \n            // Only accept values that are [0, maxMultiple), this ensures they can\n            // be evenly mapped to indices of `chars` via a modulo operation.\n            n.length < 20 && r[i] < t && (n += e.charAt(r[i] % e.length));\n        }\n        return n;\n    }\n}\n\nfunction __PRIVATE_primitiveComparator(e, t) {\n    return e < t ? -1 : e > t ? 1 : 0;\n}\n\n/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(e, t, n) {\n    return e.length === t.length && e.every(((e, r) => n(e, t[r])));\n}\n\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */ function __PRIVATE_immediateSuccessor(e) {\n    // Return the input string, with an additional NUL byte appended.\n    return e + \"\\0\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nclass Timestamp {\n    /**\n     * Creates a new timestamp.\n     *\n     * @param seconds - The number of seconds of UTC time since Unix epoch\n     *     1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n     *     9999-12-31T23:59:59Z inclusive.\n     * @param nanoseconds - The non-negative fractions of a second at nanosecond\n     *     resolution. Negative second values with fractions must still have\n     *     non-negative nanoseconds values that count forward in time. Must be\n     *     from 0 to 999,999,999 inclusive.\n     */\n    constructor(\n    /**\n     * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n     */\n    e, \n    /**\n     * The fractions of a second at nanosecond resolution.*\n     */\n    t) {\n        if (this.seconds = e, this.nanoseconds = t, t < 0) throw new FirestoreError(v.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + t);\n        if (t >= 1e9) throw new FirestoreError(v.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + t);\n        if (e < -62135596800) throw new FirestoreError(v.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + e);\n        // This will break in the year 10,000.\n                if (e >= 253402300800) throw new FirestoreError(v.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + e);\n    }\n    /**\n     * Creates a new timestamp with the current date, with millisecond precision.\n     *\n     * @returns a new timestamp representing the current date.\n     */    static now() {\n        return Timestamp.fromMillis(Date.now());\n    }\n    /**\n     * Creates a new timestamp from the given date.\n     *\n     * @param date - The date to initialize the `Timestamp` from.\n     * @returns A new `Timestamp` representing the same point in time as the given\n     *     date.\n     */    static fromDate(e) {\n        return Timestamp.fromMillis(e.getTime());\n    }\n    /**\n     * Creates a new timestamp from the given number of milliseconds.\n     *\n     * @param milliseconds - Number of milliseconds since Unix epoch\n     *     1970-01-01T00:00:00Z.\n     * @returns A new `Timestamp` representing the same point in time as the given\n     *     number of milliseconds.\n     */    static fromMillis(e) {\n        const t = Math.floor(e / 1e3), n = Math.floor(1e6 * (e - 1e3 * t));\n        return new Timestamp(t, n);\n    }\n    /**\n     * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n     * causes a loss of precision since `Date` objects only support millisecond\n     * precision.\n     *\n     * @returns JavaScript `Date` object representing the same point in time as\n     *     this `Timestamp`, with millisecond precision.\n     */    toDate() {\n        return new Date(this.toMillis());\n    }\n    /**\n     * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n     * epoch). This operation causes a loss of precision.\n     *\n     * @returns The point in time corresponding to this timestamp, represented as\n     *     the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n     */    toMillis() {\n        return 1e3 * this.seconds + this.nanoseconds / 1e6;\n    }\n    _compareTo(e) {\n        return this.seconds === e.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, e.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, e.seconds);\n    }\n    /**\n     * Returns true if this `Timestamp` is equal to the provided one.\n     *\n     * @param other - The `Timestamp` to compare against.\n     * @returns true if this `Timestamp` is equal to the provided one.\n     */    isEqual(e) {\n        return e.seconds === this.seconds && e.nanoseconds === this.nanoseconds;\n    }\n    /** Returns a textual representation of this `Timestamp`. */    toString() {\n        return \"Timestamp(seconds=\" + this.seconds + \", nanoseconds=\" + this.nanoseconds + \")\";\n    }\n    /** Returns a JSON-serializable representation of this `Timestamp`. */    toJSON() {\n        return {\n            seconds: this.seconds,\n            nanoseconds: this.nanoseconds\n        };\n    }\n    /**\n     * Converts this object to a primitive string, which allows `Timestamp` objects\n     * to be compared using the `>`, `<=`, `>=` and `>` operators.\n     */    valueOf() {\n        // This method returns a string of the form <seconds>.<nanoseconds> where\n        // <seconds> is translated to have a non-negative value and both <seconds>\n        // and <nanoseconds> are left-padded with zeroes to be a consistent length.\n        // Strings with this format then have a lexiographical ordering that matches\n        // the expected ordering. The <seconds> translation is done to avoid having\n        // a leading negative sign (i.e. a leading '-' character) in its string\n        // representation, which would affect its lexiographical ordering.\n        const e = this.seconds - -62135596800;\n        // Note: Up to 12 decimal digits are required to represent all valid\n        // 'seconds' values.\n                return String(e).padStart(12, \"0\") + \".\" + String(this.nanoseconds).padStart(9, \"0\");\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */ class SnapshotVersion {\n    constructor(e) {\n        this.timestamp = e;\n    }\n    static fromTimestamp(e) {\n        return new SnapshotVersion(e);\n    }\n    static min() {\n        return new SnapshotVersion(new Timestamp(0, 0));\n    }\n    static max() {\n        return new SnapshotVersion(new Timestamp(253402300799, 999999999));\n    }\n    compareTo(e) {\n        return this.timestamp._compareTo(e.timestamp);\n    }\n    isEqual(e) {\n        return this.timestamp.isEqual(e.timestamp);\n    }\n    /** Returns a number representation of the version for use in spec tests. */    toMicroseconds() {\n        // Convert to microseconds.\n        return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;\n    }\n    toString() {\n        return \"SnapshotVersion(\" + this.timestamp.toString() + \")\";\n    }\n    toTimestamp() {\n        return this.timestamp;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Path represents an ordered sequence of string segments.\n */\nclass BasePath {\n    constructor(e, t, n) {\n        void 0 === t ? t = 0 : t > e.length && fail(), void 0 === n ? n = e.length - t : n > e.length - t && fail(), \n        this.segments = e, this.offset = t, this.len = n;\n    }\n    get length() {\n        return this.len;\n    }\n    isEqual(e) {\n        return 0 === BasePath.comparator(this, e);\n    }\n    child(e) {\n        const t = this.segments.slice(this.offset, this.limit());\n        return e instanceof BasePath ? e.forEach((e => {\n            t.push(e);\n        })) : t.push(e), this.construct(t);\n    }\n    /** The index of one past the last segment of the path. */    limit() {\n        return this.offset + this.length;\n    }\n    popFirst(e) {\n        return e = void 0 === e ? 1 : e, this.construct(this.segments, this.offset + e, this.length - e);\n    }\n    popLast() {\n        return this.construct(this.segments, this.offset, this.length - 1);\n    }\n    firstSegment() {\n        return this.segments[this.offset];\n    }\n    lastSegment() {\n        return this.get(this.length - 1);\n    }\n    get(e) {\n        return this.segments[this.offset + e];\n    }\n    isEmpty() {\n        return 0 === this.length;\n    }\n    isPrefixOf(e) {\n        if (e.length < this.length) return !1;\n        for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1;\n        return !0;\n    }\n    isImmediateParentOf(e) {\n        if (this.length + 1 !== e.length) return !1;\n        for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1;\n        return !0;\n    }\n    forEach(e) {\n        for (let t = this.offset, n = this.limit(); t < n; t++) e(this.segments[t]);\n    }\n    toArray() {\n        return this.segments.slice(this.offset, this.limit());\n    }\n    static comparator(e, t) {\n        const n = Math.min(e.length, t.length);\n        for (let r = 0; r < n; r++) {\n            const n = e.get(r), i = t.get(r);\n            if (n < i) return -1;\n            if (n > i) return 1;\n        }\n        return e.length < t.length ? -1 : e.length > t.length ? 1 : 0;\n    }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */ class ResourcePath extends BasePath {\n    construct(e, t, n) {\n        return new ResourcePath(e, t, n);\n    }\n    canonicalString() {\n        // NOTE: The client is ignorant of any path segments containing escape\n        // sequences (e.g. __id123__) and just passes them through raw (they exist\n        // for legacy reasons and should not be used frequently).\n        return this.toArray().join(\"/\");\n    }\n    toString() {\n        return this.canonicalString();\n    }\n    /**\n     * Creates a resource path from the given slash-delimited string. If multiple\n     * arguments are provided, all components are combined. Leading and trailing\n     * slashes from all components are ignored.\n     */    static fromString(...e) {\n        // NOTE: The client is ignorant of any path segments containing escape\n        // sequences (e.g. __id123__) and just passes them through raw (they exist\n        // for legacy reasons and should not be used frequently).\n        const t = [];\n        for (const n of e) {\n            if (n.indexOf(\"//\") >= 0) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);\n            // Strip leading and traling slashed.\n                        t.push(...n.split(\"/\").filter((e => e.length > 0)));\n        }\n        return new ResourcePath(t);\n    }\n    static emptyPath() {\n        return new ResourcePath([]);\n    }\n}\n\nconst C = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */ class FieldPath$1 extends BasePath {\n    construct(e, t, n) {\n        return new FieldPath$1(e, t, n);\n    }\n    /**\n     * Returns true if the string could be used as a segment in a field path\n     * without escaping.\n     */    static isValidIdentifier(e) {\n        return C.test(e);\n    }\n    canonicalString() {\n        return this.toArray().map((e => (e = e.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\"), \n        FieldPath$1.isValidIdentifier(e) || (e = \"`\" + e + \"`\"), e))).join(\".\");\n    }\n    toString() {\n        return this.canonicalString();\n    }\n    /**\n     * Returns true if this field references the key of a document.\n     */    isKeyField() {\n        return 1 === this.length && \"__name__\" === this.get(0);\n    }\n    /**\n     * The field designating the key of a document.\n     */    static keyField() {\n        return new FieldPath$1([ \"__name__\" ]);\n    }\n    /**\n     * Parses a field string from the given server-formatted string.\n     *\n     * - Splitting the empty string is not allowed (for now at least).\n     * - Empty segments within the string (e.g. if there are two consecutive\n     *   separators) are not allowed.\n     *\n     * TODO(b/37244157): we should make this more strict. Right now, it allows\n     * non-identifier path components, even if they aren't escaped.\n     */    static fromServerFormat(e) {\n        const t = [];\n        let n = \"\", r = 0;\n        const __PRIVATE_addCurrentSegment = () => {\n            if (0 === n.length) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);\n            t.push(n), n = \"\";\n        };\n        let i = !1;\n        for (;r < e.length; ) {\n            const t = e[r];\n            if (\"\\\\\" === t) {\n                if (r + 1 === e.length) throw new FirestoreError(v.INVALID_ARGUMENT, \"Path has trailing escape character: \" + e);\n                const t = e[r + 1];\n                if (\"\\\\\" !== t && \".\" !== t && \"`\" !== t) throw new FirestoreError(v.INVALID_ARGUMENT, \"Path has invalid escape sequence: \" + e);\n                n += t, r += 2;\n            } else \"`\" === t ? (i = !i, r++) : \".\" !== t || i ? (n += t, r++) : (__PRIVATE_addCurrentSegment(), \n            r++);\n        }\n        if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(v.INVALID_ARGUMENT, \"Unterminated ` in path: \" + e);\n        return new FieldPath$1(t);\n    }\n    static emptyPath() {\n        return new FieldPath$1([]);\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */ class DocumentKey {\n    constructor(e) {\n        this.path = e;\n    }\n    static fromPath(e) {\n        return new DocumentKey(ResourcePath.fromString(e));\n    }\n    static fromName(e) {\n        return new DocumentKey(ResourcePath.fromString(e).popFirst(5));\n    }\n    static empty() {\n        return new DocumentKey(ResourcePath.emptyPath());\n    }\n    get collectionGroup() {\n        return this.path.popLast().lastSegment();\n    }\n    /** Returns true if the document is in the specified collectionId. */    hasCollectionId(e) {\n        return this.path.length >= 2 && this.path.get(this.path.length - 2) === e;\n    }\n    /** Returns the collection group (i.e. the name of the parent collection) for this key. */    getCollectionGroup() {\n        return this.path.get(this.path.length - 2);\n    }\n    /** Returns the fully qualified path to the parent collection. */    getCollectionPath() {\n        return this.path.popLast();\n    }\n    isEqual(e) {\n        return null !== e && 0 === ResourcePath.comparator(this.path, e.path);\n    }\n    toString() {\n        return this.path.toString();\n    }\n    static comparator(e, t) {\n        return ResourcePath.comparator(e.path, t.path);\n    }\n    static isDocumentKey(e) {\n        return e.length % 2 == 0;\n    }\n    /**\n     * Creates and returns a new document key with the given segments.\n     *\n     * @param segments - The segments of the path to the document\n     * @returns A new instance of DocumentKey\n     */    static fromSegments(e) {\n        return new DocumentKey(new ResourcePath(e.slice()));\n    }\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nclass FieldIndex {\n    constructor(\n    /**\n     * The index ID. Returns -1 if the index ID is not available (e.g. the index\n     * has not yet been persisted).\n     */\n    e, \n    /** The collection ID this index applies to. */\n    t, \n    /** The field segments for this index. */\n    n, \n    /** Shows how up-to-date the index is for the current user. */\n    r) {\n        this.indexId = e, this.collectionGroup = t, this.fields = n, this.indexState = r;\n    }\n}\n\n/** An ID for an index that has not yet been added to persistence.  */\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nfunction __PRIVATE_fieldIndexGetArraySegment(e) {\n    return e.fields.find((e => 2 /* IndexKind.CONTAINS */ === e.kind));\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */ function __PRIVATE_fieldIndexGetDirectionalSegments(e) {\n    return e.fields.filter((e => 2 /* IndexKind.CONTAINS */ !== e.kind));\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nfunction __PRIVATE_fieldIndexSemanticComparator(e, t) {\n    let n = __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup);\n    if (0 !== n) return n;\n    for (let r = 0; r < Math.min(e.fields.length, t.fields.length); ++r) if (n = __PRIVATE_indexSegmentComparator(e.fields[r], t.fields[r]), \n    0 !== n) return n;\n    return __PRIVATE_primitiveComparator(e.fields.length, t.fields.length);\n}\n\n/** Returns a debug representation of the field index */ FieldIndex.UNKNOWN_ID = -1;\n\n/** An index component consisting of field path and index type.  */\nclass IndexSegment {\n    constructor(\n    /** The field path of the component. */\n    e, \n    /** The fields sorting order. */\n    t) {\n        this.fieldPath = e, this.kind = t;\n    }\n}\n\nfunction __PRIVATE_indexSegmentComparator(e, t) {\n    const n = FieldPath$1.comparator(e.fieldPath, t.fieldPath);\n    return 0 !== n ? n : __PRIVATE_primitiveComparator(e.kind, t.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */ class IndexState {\n    constructor(\n    /**\n     * Indicates when the index was last updated (relative to other indexes).\n     */\n    e, \n    /** The the latest indexed read time, document and batch id. */\n    t) {\n        this.sequenceNumber = e, this.offset = t;\n    }\n    /** The state of an index that has not yet been backfilled. */    static empty() {\n        return new IndexState(0, IndexOffset.min());\n    }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */ function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e, t) {\n    // We want to create an offset that matches all documents with a read time\n    // greater than the provided read time. To do so, we technically need to\n    // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n    // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n    // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n    // all valid document IDs.\n    const n = e.toTimestamp().seconds, r = e.toTimestamp().nanoseconds + 1, i = SnapshotVersion.fromTimestamp(1e9 === r ? new Timestamp(n + 1, 0) : new Timestamp(n, r));\n    return new IndexOffset(i, DocumentKey.empty(), t);\n}\n\n/** Creates a new offset based on the provided document. */ function __PRIVATE_newIndexOffsetFromDocument(e) {\n    return new IndexOffset(e.readTime, e.key, -1);\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */ class IndexOffset {\n    constructor(\n    /**\n     * The latest read time version that has been indexed by Firestore for this\n     * field index.\n     */\n    e, \n    /**\n     * The key of the last document that was indexed for this query. Use\n     * `DocumentKey.empty()` if no document has been indexed.\n     */\n    t, \n    /*\n     * The largest mutation batch id that's been processed by Firestore.\n     */\n    n) {\n        this.readTime = e, this.documentKey = t, this.largestBatchId = n;\n    }\n    /** Returns an offset that sorts before all regular offsets. */    static min() {\n        return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), -1);\n    }\n    /** Returns an offset that sorts after all regular offsets. */    static max() {\n        return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), -1);\n    }\n}\n\nfunction __PRIVATE_indexOffsetComparator(e, t) {\n    let n = e.readTime.compareTo(t.readTime);\n    return 0 !== n ? n : (n = DocumentKey.comparator(e.documentKey, t.documentKey), \n    0 !== n ? n : __PRIVATE_primitiveComparator(e.largestBatchId, t.largestBatchId));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const F = \"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.\";\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */ class PersistenceTransaction {\n    constructor() {\n        this.onCommittedListeners = [];\n    }\n    addOnCommittedListener(e) {\n        this.onCommittedListeners.push(e);\n    }\n    raiseOnCommittedEvent() {\n        this.onCommittedListeners.forEach((e => e()));\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */ async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e) {\n    if (e.code !== v.FAILED_PRECONDITION || e.message !== F) throw e;\n    __PRIVATE_logDebug(\"LocalStore\", \"Unexpectedly lost primary lease\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */ class PersistencePromise {\n    constructor(e) {\n        // NOTE: next/catchCallback will always point to our own wrapper functions,\n        // not the user's raw next() or catch() callbacks.\n        this.nextCallback = null, this.catchCallback = null, \n        // When the operation resolves, we'll set result or error and mark isDone.\n        this.result = void 0, this.error = void 0, this.isDone = !1, \n        // Set to true when .then() or .catch() are called and prevents additional\n        // chaining.\n        this.callbackAttached = !1, e((e => {\n            this.isDone = !0, this.result = e, this.nextCallback && \n            // value should be defined unless T is Void, but we can't express\n            // that in the type system.\n            this.nextCallback(e);\n        }), (e => {\n            this.isDone = !0, this.error = e, this.catchCallback && this.catchCallback(e);\n        }));\n    }\n    catch(e) {\n        return this.next(void 0, e);\n    }\n    next(e, t) {\n        return this.callbackAttached && fail(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(t, this.error) : this.wrapSuccess(e, this.result) : new PersistencePromise(((n, r) => {\n            this.nextCallback = t => {\n                this.wrapSuccess(e, t).next(n, r);\n            }, this.catchCallback = e => {\n                this.wrapFailure(t, e).next(n, r);\n            };\n        }));\n    }\n    toPromise() {\n        return new Promise(((e, t) => {\n            this.next(e, t);\n        }));\n    }\n    wrapUserFunction(e) {\n        try {\n            const t = e();\n            return t instanceof PersistencePromise ? t : PersistencePromise.resolve(t);\n        } catch (e) {\n            return PersistencePromise.reject(e);\n        }\n    }\n    wrapSuccess(e, t) {\n        return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.resolve(t);\n    }\n    wrapFailure(e, t) {\n        return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.reject(t);\n    }\n    static resolve(e) {\n        return new PersistencePromise(((t, n) => {\n            t(e);\n        }));\n    }\n    static reject(e) {\n        return new PersistencePromise(((t, n) => {\n            n(e);\n        }));\n    }\n    static waitFor(\n    // Accept all Promise types in waitFor().\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    e) {\n        return new PersistencePromise(((t, n) => {\n            let r = 0, i = 0, s = !1;\n            e.forEach((e => {\n                ++r, e.next((() => {\n                    ++i, s && i === r && t();\n                }), (e => n(e)));\n            })), s = !0, i === r && t();\n        }));\n    }\n    /**\n     * Given an array of predicate functions that asynchronously evaluate to a\n     * boolean, implements a short-circuiting `or` between the results. Predicates\n     * will be evaluated until one of them returns `true`, then stop. The final\n     * result will be whether any of them returned `true`.\n     */    static or(e) {\n        let t = PersistencePromise.resolve(!1);\n        for (const n of e) t = t.next((e => e ? PersistencePromise.resolve(e) : n()));\n        return t;\n    }\n    static forEach(e, t) {\n        const n = [];\n        return e.forEach(((e, r) => {\n            n.push(t.call(this, e, r));\n        })), this.waitFor(n);\n    }\n    /**\n     * Concurrently map all array elements through asynchronous function.\n     */    static mapArray(e, t) {\n        return new PersistencePromise(((n, r) => {\n            const i = e.length, s = new Array(i);\n            let o = 0;\n            for (let _ = 0; _ < i; _++) {\n                const a = _;\n                t(e[a]).next((e => {\n                    s[a] = e, ++o, o === i && n(s);\n                }), (e => r(e)));\n            }\n        }));\n    }\n    /**\n     * An alternative to recursive PersistencePromise calls, that avoids\n     * potential memory problems from unbounded chains of promises.\n     *\n     * The `action` will be called repeatedly while `condition` is true.\n     */    static doWhile(e, t) {\n        return new PersistencePromise(((n, r) => {\n            const process = () => {\n                !0 === e() ? t().next((() => {\n                    process();\n                }), r) : n();\n            };\n            process();\n        }));\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nclass __PRIVATE_SimpleDbTransaction {\n    constructor(e, t) {\n        this.action = e, this.transaction = t, this.aborted = !1, \n        /**\n         * A `Promise` that resolves with the result of the IndexedDb transaction.\n         */\n        this.m = new __PRIVATE_Deferred, this.transaction.oncomplete = () => {\n            this.m.resolve();\n        }, this.transaction.onabort = () => {\n            t.error ? this.m.reject(new __PRIVATE_IndexedDbTransactionError(e, t.error)) : this.m.resolve();\n        }, this.transaction.onerror = t => {\n            const n = __PRIVATE_checkForAndReportiOSError(t.target.error);\n            this.m.reject(new __PRIVATE_IndexedDbTransactionError(e, n));\n        };\n    }\n    static open(e, t, n, r) {\n        try {\n            return new __PRIVATE_SimpleDbTransaction(t, e.transaction(r, n));\n        } catch (e) {\n            throw new __PRIVATE_IndexedDbTransactionError(t, e);\n        }\n    }\n    get g() {\n        return this.m.promise;\n    }\n    abort(e) {\n        e && this.m.reject(e), this.aborted || (__PRIVATE_logDebug(\"SimpleDb\", \"Aborting transaction:\", e ? e.message : \"Client-initiated abort\"), \n        this.aborted = !0, this.transaction.abort());\n    }\n    p() {\n        // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n        // speed up index DB processing if the event loop remains blocks.\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        const e = this.transaction;\n        this.aborted || \"function\" != typeof e.commit || e.commit();\n    }\n    /**\n     * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All\n     * operations performed on the SimpleDbStore happen within the context of this\n     * transaction and it cannot be used anymore once the transaction is\n     * completed.\n     *\n     * Note that we can't actually enforce that the KeyType and ValueType are\n     * correct, but they allow type safety through the rest of the consuming code.\n     */    store(e) {\n        const t = this.transaction.objectStore(e);\n        return new __PRIVATE_SimpleDbStore(t);\n    }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */ class __PRIVATE_SimpleDb {\n    /*\n     * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n     *\n     * Note that `version` must not be a downgrade. IndexedDB does not support\n     * downgrading the schema version. We currently do not support any way to do\n     * versioning outside of IndexedDB's versioning mechanism, as only\n     * version-upgrade transactions are allowed to do things like create\n     * objectstores.\n     */\n    constructor(e, t, n) {\n        this.name = e, this.version = t, this.S = n;\n        // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n        // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n        // whatever reason it's much harder to hit after 12.2 so we only proactively\n        // log on 12.2.\n        12.2 === __PRIVATE_SimpleDb.D(getUA()) && __PRIVATE_logError(\"Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.\");\n    }\n    /** Deletes the specified database. */    static delete(e) {\n        return __PRIVATE_logDebug(\"SimpleDb\", \"Removing database:\", e), __PRIVATE_wrapRequest(window.indexedDB.deleteDatabase(e)).toPromise();\n    }\n    /** Returns true if IndexedDB is available in the current environment. */    static v() {\n        if (!isIndexedDBAvailable()) return !1;\n        if (__PRIVATE_SimpleDb.C()) return !0;\n        // We extensively use indexed array values and compound keys,\n        // which IE and Edge do not support. However, they still have indexedDB\n        // defined on the window, so we need to check for them here and make sure\n        // to return that persistence is not enabled for those browsers.\n        // For tracking support of this feature, see here:\n        // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n        // Check the UA string to find out the browser.\n                const e = getUA(), t = __PRIVATE_SimpleDb.D(e), n = 0 < t && t < 10, r = __PRIVATE_SimpleDb.F(e), i = 0 < r && r < 4.5;\n        // IE 10\n        // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n        // IE 11\n        // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n        // Edge\n        // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n        // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n        // iOS Safari: Disable for users running iOS version < 10.\n                return !(e.indexOf(\"MSIE \") > 0 || e.indexOf(\"Trident/\") > 0 || e.indexOf(\"Edge/\") > 0 || n || i);\n    }\n    /**\n     * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n     * (see https://github.com/axemclion/IndexedDBShim).\n     */    static C() {\n        var e;\n        return \"undefined\" != typeof process && \"YES\" === (null === (e = process.env) || void 0 === e ? void 0 : e.M);\n    }\n    /** Helper to get a typed SimpleDbStore from a transaction. */    static O(e, t) {\n        return e.store(t);\n    }\n    // visible for testing\n    /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n    static D(e) {\n        const t = e.match(/i(?:phone|pad|pod) os ([\\d_]+)/i), n = t ? t[1].split(\"_\").slice(0, 2).join(\".\") : \"-1\";\n        return Number(n);\n    }\n    // visible for testing\n    /** Parse User Agent to determine Android version. Returns -1 if not found. */\n    static F(e) {\n        const t = e.match(/Android ([\\d.]+)/i), n = t ? t[1].split(\".\").slice(0, 2).join(\".\") : \"-1\";\n        return Number(n);\n    }\n    /**\n     * Opens the specified database, creating or upgrading it if necessary.\n     */    async N(e) {\n        return this.db || (__PRIVATE_logDebug(\"SimpleDb\", \"Opening database:\", this.name), \n        this.db = await new Promise(((t, n) => {\n            // TODO(mikelehen): Investigate browser compatibility.\n            // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n            // suggests IE9 and older WebKit browsers handle upgrade\n            // differently. They expect setVersion, as described here:\n            // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n            const r = indexedDB.open(this.name, this.version);\n            r.onsuccess = e => {\n                const n = e.target.result;\n                t(n);\n            }, r.onblocked = () => {\n                n(new __PRIVATE_IndexedDbTransactionError(e, \"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.\"));\n            }, r.onerror = t => {\n                const r = t.target.error;\n                \"VersionError\" === r.name ? n(new FirestoreError(v.FAILED_PRECONDITION, \"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.\")) : \"InvalidStateError\" === r.name ? n(new FirestoreError(v.FAILED_PRECONDITION, \"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: \" + r)) : n(new __PRIVATE_IndexedDbTransactionError(e, r));\n            }, r.onupgradeneeded = e => {\n                __PRIVATE_logDebug(\"SimpleDb\", 'Database \"' + this.name + '\" requires upgrade from version:', e.oldVersion);\n                const t = e.target.result;\n                this.S.B(t, r.transaction, e.oldVersion, this.version).next((() => {\n                    __PRIVATE_logDebug(\"SimpleDb\", \"Database upgrade to version \" + this.version + \" complete\");\n                }));\n            };\n        }))), this.L && (this.db.onversionchange = e => this.L(e)), this.db;\n    }\n    k(e) {\n        this.L = e, this.db && (this.db.onversionchange = t => e(t));\n    }\n    async runTransaction(e, t, n, r) {\n        const i = \"readonly\" === t;\n        let s = 0;\n        for (;;) {\n            ++s;\n            try {\n                this.db = await this.N(e);\n                const t = __PRIVATE_SimpleDbTransaction.open(this.db, e, i ? \"readonly\" : \"readwrite\", n), s = r(t).next((e => (t.p(), \n                e))).catch((e => (\n                // Abort the transaction if there was an error.\n                t.abort(e), PersistencePromise.reject(e)))).toPromise();\n                // As noted above, errors are propagated by aborting the transaction. So\n                // we swallow any error here to avoid the browser logging it as unhandled.\n                return s.catch((() => {})), \n                // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n                // fire), but still return the original transactionFnResult back to the\n                // caller.\n                await t.g, s;\n            } catch (e) {\n                const t = e, n = \"FirebaseError\" !== t.name && s < 3;\n                // TODO(schmidt-sebastian): We could probably be smarter about this and\n                // not retry exceptions that are likely unrecoverable (such as quota\n                // exceeded errors).\n                // Note: We cannot use an instanceof check for FirestoreException, since the\n                // exception is wrapped in a generic error by our async/await handling.\n                                if (__PRIVATE_logDebug(\"SimpleDb\", \"Transaction failed with error:\", t.message, \"Retrying:\", n), \n                this.close(), !n) return Promise.reject(t);\n            }\n        }\n    }\n    close() {\n        this.db && this.db.close(), this.db = void 0;\n    }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */ class __PRIVATE_IterationController {\n    constructor(e) {\n        this.q = e, this.K = !1, this.$ = null;\n    }\n    get isDone() {\n        return this.K;\n    }\n    get U() {\n        return this.$;\n    }\n    set cursor(e) {\n        this.q = e;\n    }\n    /**\n     * This function can be called to stop iteration at any point.\n     */    done() {\n        this.K = !0;\n    }\n    /**\n     * This function can be called to skip to that next key, which could be\n     * an index or a primary key.\n     */    W(e) {\n        this.$ = e;\n    }\n    /**\n     * Delete the current cursor value from the object store.\n     *\n     * NOTE: You CANNOT do this with a keysOnly query.\n     */    delete() {\n        return __PRIVATE_wrapRequest(this.q.delete());\n    }\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */ class __PRIVATE_IndexedDbTransactionError extends FirestoreError {\n    constructor(e, t) {\n        super(v.UNAVAILABLE, `IndexedDB transaction '${e}' failed: ${t}`), this.name = \"IndexedDbTransactionError\";\n    }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */ function __PRIVATE_isIndexedDbTransactionError(e) {\n    // Use name equality, as instanceof checks on errors don't work with errors\n    // that wrap other errors.\n    return \"IndexedDbTransactionError\" === e.name;\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */ class __PRIVATE_SimpleDbStore {\n    constructor(e) {\n        this.store = e;\n    }\n    put(e, t) {\n        let n;\n        return void 0 !== t ? (__PRIVATE_logDebug(\"SimpleDb\", \"PUT\", this.store.name, e, t), \n        n = this.store.put(t, e)) : (__PRIVATE_logDebug(\"SimpleDb\", \"PUT\", this.store.name, \"<auto-key>\", e), \n        n = this.store.put(e)), __PRIVATE_wrapRequest(n);\n    }\n    /**\n     * Adds a new value into an Object Store and returns the new key. Similar to\n     * IndexedDb's `add()`, this method will fail on primary key collisions.\n     *\n     * @param value - The object to write.\n     * @returns The key of the value to add.\n     */    add(e) {\n        __PRIVATE_logDebug(\"SimpleDb\", \"ADD\", this.store.name, e, e);\n        return __PRIVATE_wrapRequest(this.store.add(e));\n    }\n    /**\n     * Gets the object with the specified key from the specified store, or null\n     * if no object exists with the specified key.\n     *\n     * @key The key of the object to get.\n     * @returns The object with the specified key or null if no object exists.\n     */    get(e) {\n        // We're doing an unsafe cast to ValueType.\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        return __PRIVATE_wrapRequest(this.store.get(e)).next((t => (\n        // Normalize nonexistence to null.\n        void 0 === t && (t = null), __PRIVATE_logDebug(\"SimpleDb\", \"GET\", this.store.name, e, t), \n        t)));\n    }\n    delete(e) {\n        __PRIVATE_logDebug(\"SimpleDb\", \"DELETE\", this.store.name, e);\n        return __PRIVATE_wrapRequest(this.store.delete(e));\n    }\n    /**\n     * If we ever need more of the count variants, we can add overloads. For now,\n     * all we need is to count everything in a store.\n     *\n     * Returns the number of rows in the store.\n     */    count() {\n        __PRIVATE_logDebug(\"SimpleDb\", \"COUNT\", this.store.name);\n        return __PRIVATE_wrapRequest(this.store.count());\n    }\n    G(e, t) {\n        const n = this.options(e, t);\n        // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n        // 20% faster. Unfortunately, getAll() does not support custom indices.\n                if (n.index || \"function\" != typeof this.store.getAll) {\n            const e = this.cursor(n), t = [];\n            return this.j(e, ((e, n) => {\n                t.push(n);\n            })).next((() => t));\n        }\n        {\n            const e = this.store.getAll(n.range);\n            return new PersistencePromise(((t, n) => {\n                e.onerror = e => {\n                    n(e.target.error);\n                }, e.onsuccess = e => {\n                    t(e.target.result);\n                };\n            }));\n        }\n    }\n    /**\n     * Loads the first `count` elements from the provided index range. Loads all\n     * elements if no limit is provided.\n     */    H(e, t) {\n        const n = this.store.getAll(e, null === t ? void 0 : t);\n        return new PersistencePromise(((e, t) => {\n            n.onerror = e => {\n                t(e.target.error);\n            }, n.onsuccess = t => {\n                e(t.target.result);\n            };\n        }));\n    }\n    J(e, t) {\n        __PRIVATE_logDebug(\"SimpleDb\", \"DELETE ALL\", this.store.name);\n        const n = this.options(e, t);\n        n.Y = !1;\n        const r = this.cursor(n);\n        return this.j(r, ((e, t, n) => n.delete()));\n    }\n    Z(e, t) {\n        let n;\n        t ? n = e : (n = {}, t = e);\n        const r = this.cursor(n);\n        return this.j(r, t);\n    }\n    /**\n     * Iterates over a store, but waits for the given callback to complete for\n     * each entry before iterating the next entry. This allows the callback to do\n     * asynchronous work to determine if this iteration should continue.\n     *\n     * The provided callback should return `true` to continue iteration, and\n     * `false` otherwise.\n     */    X(e) {\n        const t = this.cursor({});\n        return new PersistencePromise(((n, r) => {\n            t.onerror = e => {\n                const t = __PRIVATE_checkForAndReportiOSError(e.target.error);\n                r(t);\n            }, t.onsuccess = t => {\n                const r = t.target.result;\n                r ? e(r.primaryKey, r.value).next((e => {\n                    e ? r.continue() : n();\n                })) : n();\n            };\n        }));\n    }\n    j(e, t) {\n        const n = [];\n        return new PersistencePromise(((r, i) => {\n            e.onerror = e => {\n                i(e.target.error);\n            }, e.onsuccess = e => {\n                const i = e.target.result;\n                if (!i) return void r();\n                const s = new __PRIVATE_IterationController(i), o = t(i.primaryKey, i.value, s);\n                if (o instanceof PersistencePromise) {\n                    const e = o.catch((e => (s.done(), PersistencePromise.reject(e))));\n                    n.push(e);\n                }\n                s.isDone ? r() : null === s.U ? i.continue() : i.continue(s.U);\n            };\n        })).next((() => PersistencePromise.waitFor(n)));\n    }\n    options(e, t) {\n        let n;\n        return void 0 !== e && (\"string\" == typeof e ? n = e : t = e), {\n            index: n,\n            range: t\n        };\n    }\n    cursor(e) {\n        let t = \"next\";\n        if (e.reverse && (t = \"prev\"), e.index) {\n            const n = this.store.index(e.index);\n            return e.Y ? n.openKeyCursor(e.range, t) : n.openCursor(e.range, t);\n        }\n        return this.store.openCursor(e.range, t);\n    }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */ function __PRIVATE_wrapRequest(e) {\n    return new PersistencePromise(((t, n) => {\n        e.onsuccess = e => {\n            const n = e.target.result;\n            t(n);\n        }, e.onerror = e => {\n            const t = __PRIVATE_checkForAndReportiOSError(e.target.error);\n            n(t);\n        };\n    }));\n}\n\n// Guard so we only report the error once.\nlet M = !1;\n\nfunction __PRIVATE_checkForAndReportiOSError(e) {\n    const t = __PRIVATE_SimpleDb.D(getUA());\n    if (t >= 12.2 && t < 13) {\n        const t = \"An internal error was encountered in the Indexed Database server\";\n        if (e.message.indexOf(t) >= 0) {\n            // Wrap error in a more descriptive one.\n            const e = new FirestoreError(\"internal\", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);\n            return M || (M = !0, \n            // Throw a global exception outside of this promise chain, for the user to\n            // potentially catch.\n            setTimeout((() => {\n                throw e;\n            }), 0)), e;\n        }\n    }\n    return e;\n}\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nclass __PRIVATE_IndexBackfillerScheduler {\n    constructor(e, t) {\n        this.asyncQueue = e, this.ee = t, this.task = null;\n    }\n    start() {\n        this.te(15e3);\n    }\n    stop() {\n        this.task && (this.task.cancel(), this.task = null);\n    }\n    get started() {\n        return null !== this.task;\n    }\n    te(e) {\n        __PRIVATE_logDebug(\"IndexBackiller\", `Scheduled in ${e}ms`), this.task = this.asyncQueue.enqueueAfterDelay(\"index_backfill\" /* TimerId.IndexBackfill */ , e, (async () => {\n            this.task = null;\n            try {\n                __PRIVATE_logDebug(\"IndexBackiller\", `Documents written: ${await this.ee.ne()}`);\n            } catch (e) {\n                __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(\"IndexBackiller\", \"Ignoring IndexedDB error during index backfill: \", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n            }\n            await this.te(6e4);\n        }));\n    }\n}\n\n/** Implements the steps for backfilling indexes. */ class __PRIVATE_IndexBackfiller {\n    constructor(\n    /**\n     * LocalStore provides access to IndexManager and LocalDocumentView.\n     * These properties will update when the user changes. Consequently,\n     * making a local copy of IndexManager and LocalDocumentView will require\n     * updates over time. The simpler solution is to rely on LocalStore to have\n     * an up-to-date references to IndexManager and LocalDocumentStore.\n     */\n    e, t) {\n        this.localStore = e, this.persistence = t;\n    }\n    async ne(e = 50) {\n        return this.persistence.runTransaction(\"Backfill Indexes\", \"readwrite-primary\", (t => this.re(t, e)));\n    }\n    /** Writes index entries until the cap is reached. Returns the number of documents processed. */    re(e, t) {\n        const n = new Set;\n        let r = t, i = !0;\n        return PersistencePromise.doWhile((() => !0 === i && r > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t => {\n            if (null !== t && !n.has(t)) return __PRIVATE_logDebug(\"IndexBackiller\", `Processing collection: ${t}`), \n            this.ie(e, t, r).next((e => {\n                r -= e, n.add(t);\n            }));\n            i = !1;\n        })))).next((() => t - r));\n    }\n    /**\n     * Writes entries for the provided collection group. Returns the number of documents processed.\n     */    ie(e, t, n) {\n        // Use the earliest offset of all field indexes to query the local cache.\n        return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e, t).next((r => this.localStore.localDocuments.getNextDocuments(e, t, r, n).next((n => {\n            const i = n.changes;\n            return this.localStore.indexManager.updateIndexEntries(e, i).next((() => this.se(r, n))).next((n => (__PRIVATE_logDebug(\"IndexBackiller\", `Updating offset: ${n}`), \n            this.localStore.indexManager.updateCollectionGroup(e, t, n)))).next((() => i.size));\n        }))));\n    }\n    /** Returns the next offset based on the provided documents. */    se(e, t) {\n        let n = e;\n        return t.changes.forEach(((e, t) => {\n            const r = __PRIVATE_newIndexOffsetFromDocument(t);\n            __PRIVATE_indexOffsetComparator(r, n) > 0 && (n = r);\n        })), new IndexOffset(n.readTime, n.documentKey, Math.max(t.batchId, e.largestBatchId));\n    }\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */ class __PRIVATE_ListenSequence {\n    constructor(e, t) {\n        this.previousValue = e, t && (t.sequenceNumberHandler = e => this.oe(e), this._e = e => t.writeSequenceNumber(e));\n    }\n    oe(e) {\n        return this.previousValue = Math.max(e, this.previousValue), this.previousValue;\n    }\n    next() {\n        const e = ++this.previousValue;\n        return this._e && this._e(e), e;\n    }\n}\n\n__PRIVATE_ListenSequence.ae = -1;\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction __PRIVATE_isNullOrUndefined(e) {\n    return null == e;\n}\n\n/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(e) {\n    // Detect if the value is -0.0. Based on polyfill from\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n    return 0 === e && 1 / e == -1 / 0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */ function isSafeInteger(e) {\n    return \"number\" == typeof e && Number.isInteger(e) && !__PRIVATE_isNegativeZero(e) && e <= Number.MAX_SAFE_INTEGER && e >= Number.MIN_SAFE_INTEGER;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction __PRIVATE_encodeResourcePath(e) {\n    let t = \"\";\n    for (let n = 0; n < e.length; n++) t.length > 0 && (t = __PRIVATE_encodeSeparator(t)), \n    t = __PRIVATE_encodeSegment(e.get(n), t);\n    return __PRIVATE_encodeSeparator(t);\n}\n\n/** Encodes a single segment of a resource path into the given result */ function __PRIVATE_encodeSegment(e, t) {\n    let n = t;\n    const r = e.length;\n    for (let t = 0; t < r; t++) {\n        const r = e.charAt(t);\n        switch (r) {\n          case \"\\0\":\n            n += \"\u0001\u0010\";\n            break;\n\n          case \"\u0001\":\n            n += \"\u0001\u0011\";\n            break;\n\n          default:\n            n += r;\n        }\n    }\n    return n;\n}\n\n/** Encodes a path separator into the given result */ function __PRIVATE_encodeSeparator(e) {\n    return e + \"\u0001\u0001\";\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */ function __PRIVATE_decodeResourcePath(e) {\n    // Event the empty path must encode as a path of at least length 2. A path\n    // with exactly 2 must be the empty path.\n    const t = e.length;\n    if (__PRIVATE_hardAssert(t >= 2), 2 === t) return __PRIVATE_hardAssert(\"\u0001\" === e.charAt(0) && \"\u0001\" === e.charAt(1)), \n    ResourcePath.emptyPath();\n    // Escape characters cannot exist past the second-to-last position in the\n    // source value.\n        const __PRIVATE_lastReasonableEscapeIndex = t - 2, n = [];\n    let r = \"\";\n    for (let i = 0; i < t; ) {\n        // The last two characters of a valid encoded path must be a separator, so\n        // there must be an end to this segment.\n        const t = e.indexOf(\"\u0001\", i);\n        (t < 0 || t > __PRIVATE_lastReasonableEscapeIndex) && fail();\n        switch (e.charAt(t + 1)) {\n          case \"\u0001\":\n            const s = e.substring(i, t);\n            let o;\n            0 === r.length ? \n            // Avoid copying for the common case of a segment that excludes \\0\n            // and \\001\n            o = s : (r += s, o = r, r = \"\"), n.push(o);\n            break;\n\n          case \"\u0010\":\n            r += e.substring(i, t), r += \"\\0\";\n            break;\n\n          case \"\u0011\":\n            // The escape character can be used in the output to encode itself.\n            r += e.substring(i, t + 1);\n            break;\n\n          default:\n            fail();\n        }\n        i = t + 2;\n    }\n    return new ResourcePath(n);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const x = [ \"userId\", \"batchId\" ];\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nfunction __PRIVATE_newDbDocumentMutationPrefixForPath(e, t) {\n    return [ e, __PRIVATE_encodeResourcePath(t) ];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */ function __PRIVATE_newDbDocumentMutationKey(e, t, n) {\n    return [ e, __PRIVATE_encodeResourcePath(t), n ];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */ const O = {}, N = [ \"prefixPath\", \"collectionGroup\", \"readTime\", \"documentId\" ], B = [ \"prefixPath\", \"collectionGroup\", \"documentId\" ], L = [ \"collectionGroup\", \"readTime\", \"prefixPath\", \"documentId\" ], k = [ \"canonicalId\", \"targetId\" ], q = [ \"targetId\", \"path\" ], Q = [ \"path\", \"targetId\" ], K = [ \"collectionId\", \"parent\" ], $ = [ \"indexId\", \"uid\" ], U = [ \"uid\", \"sequenceNumber\" ], W = [ \"indexId\", \"uid\", \"arrayValue\", \"directionalValue\", \"orderedDocumentKey\", \"documentKey\" ], G = [ \"indexId\", \"uid\", \"orderedDocumentKey\" ], z = [ \"userId\", \"collectionPath\", \"documentId\" ], j = [ \"userId\", \"collectionPath\", \"largestBatchId\" ], H = [ \"userId\", \"collectionGroup\", \"largestBatchId\" ], J = [ ...[ ...[ ...[ ...[ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocuments\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\" ], \"clientMetadata\" ], \"remoteDocumentGlobal\" ], \"collectionParents\" ], \"bundles\", \"namedQueries\" ], Y = [ ...J, \"documentOverlays\" ], Z = [ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocumentsV14\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\", \"clientMetadata\", \"remoteDocumentGlobal\", \"collectionParents\", \"bundles\", \"namedQueries\", \"documentOverlays\" ], X = Z, ee = [ ...X, \"indexConfiguration\", \"indexState\", \"indexEntries\" ];\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass __PRIVATE_IndexedDbTransaction extends PersistenceTransaction {\n    constructor(e, t) {\n        super(), this.ue = e, this.currentSequenceNumber = t;\n    }\n}\n\nfunction __PRIVATE_getStore(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    return __PRIVATE_SimpleDb.O(n.ue, t);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function __PRIVATE_objectSize(e) {\n    let t = 0;\n    for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t++;\n    return t;\n}\n\nfunction forEach(e, t) {\n    for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t(n, e[n]);\n}\n\nfunction isEmpty(e) {\n    for (const t in e) if (Object.prototype.hasOwnProperty.call(e, t)) return !1;\n    return !0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nclass SortedMap {\n    constructor(e, t) {\n        this.comparator = e, this.root = t || LLRBNode.EMPTY;\n    }\n    // Returns a copy of the map, with the specified key/value added or replaced.\n    insert(e, t) {\n        return new SortedMap(this.comparator, this.root.insert(e, t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));\n    }\n    // Returns a copy of the map, with the specified key removed.\n    remove(e) {\n        return new SortedMap(this.comparator, this.root.remove(e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));\n    }\n    // Returns the value of the node with the given key, or null.\n    get(e) {\n        let t = this.root;\n        for (;!t.isEmpty(); ) {\n            const n = this.comparator(e, t.key);\n            if (0 === n) return t.value;\n            n < 0 ? t = t.left : n > 0 && (t = t.right);\n        }\n        return null;\n    }\n    // Returns the index of the element in this sorted map, or -1 if it doesn't\n    // exist.\n    indexOf(e) {\n        // Number of nodes that were pruned when descending right\n        let t = 0, n = this.root;\n        for (;!n.isEmpty(); ) {\n            const r = this.comparator(e, n.key);\n            if (0 === r) return t + n.left.size;\n            r < 0 ? n = n.left : (\n            // Count all nodes left of the node plus the node itself\n            t += n.left.size + 1, n = n.right);\n        }\n        // Node not found\n                return -1;\n    }\n    isEmpty() {\n        return this.root.isEmpty();\n    }\n    // Returns the total number of nodes in the map.\n    get size() {\n        return this.root.size;\n    }\n    // Returns the minimum key in the map.\n    minKey() {\n        return this.root.minKey();\n    }\n    // Returns the maximum key in the map.\n    maxKey() {\n        return this.root.maxKey();\n    }\n    // Traverses the map in key order and calls the specified action function\n    // for each key/value pair. If action returns true, traversal is aborted.\n    // Returns the first truthy value returned by action, or the last falsey\n    // value returned by action.\n    inorderTraversal(e) {\n        return this.root.inorderTraversal(e);\n    }\n    forEach(e) {\n        this.inorderTraversal(((t, n) => (e(t, n), !1)));\n    }\n    toString() {\n        const e = [];\n        return this.inorderTraversal(((t, n) => (e.push(`${t}:${n}`), !1))), `{${e.join(\", \")}}`;\n    }\n    // Traverses the map in reverse key order and calls the specified action\n    // function for each key/value pair. If action returns true, traversal is\n    // aborted.\n    // Returns the first truthy value returned by action, or the last falsey\n    // value returned by action.\n    reverseTraversal(e) {\n        return this.root.reverseTraversal(e);\n    }\n    // Returns an iterator over the SortedMap.\n    getIterator() {\n        return new SortedMapIterator(this.root, null, this.comparator, !1);\n    }\n    getIteratorFrom(e) {\n        return new SortedMapIterator(this.root, e, this.comparator, !1);\n    }\n    getReverseIterator() {\n        return new SortedMapIterator(this.root, null, this.comparator, !0);\n    }\n    getReverseIteratorFrom(e) {\n        return new SortedMapIterator(this.root, e, this.comparator, !0);\n    }\n}\n\n // end SortedMap\n// An iterator over an LLRBNode.\nclass SortedMapIterator {\n    constructor(e, t, n, r) {\n        this.isReverse = r, this.nodeStack = [];\n        let i = 1;\n        for (;!e.isEmpty(); ) if (i = t ? n(e.key, t) : 1, \n        // flip the comparison if we're going in reverse\n        t && r && (i *= -1), i < 0) \n        // This node is less than our start key. ignore it\n        e = this.isReverse ? e.left : e.right; else {\n            if (0 === i) {\n                // This node is exactly equal to our start key. Push it on the stack,\n                // but stop iterating;\n                this.nodeStack.push(e);\n                break;\n            }\n            // This node is greater than our start key, add it to the stack and move\n            // to the next one\n            this.nodeStack.push(e), e = this.isReverse ? e.right : e.left;\n        }\n    }\n    getNext() {\n        let e = this.nodeStack.pop();\n        const t = {\n            key: e.key,\n            value: e.value\n        };\n        if (this.isReverse) for (e = e.left; !e.isEmpty(); ) this.nodeStack.push(e), e = e.right; else for (e = e.right; !e.isEmpty(); ) this.nodeStack.push(e), \n        e = e.left;\n        return t;\n    }\n    hasNext() {\n        return this.nodeStack.length > 0;\n    }\n    peek() {\n        if (0 === this.nodeStack.length) return null;\n        const e = this.nodeStack[this.nodeStack.length - 1];\n        return {\n            key: e.key,\n            value: e.value\n        };\n    }\n}\n\n // end SortedMapIterator\n// Represents a node in a Left-leaning Red-Black tree.\nclass LLRBNode {\n    constructor(e, t, n, r, i) {\n        this.key = e, this.value = t, this.color = null != n ? n : LLRBNode.RED, this.left = null != r ? r : LLRBNode.EMPTY, \n        this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size;\n    }\n    // Returns a copy of the current node, optionally replacing pieces of it.\n    copy(e, t, n, r, i) {\n        return new LLRBNode(null != e ? e : this.key, null != t ? t : this.value, null != n ? n : this.color, null != r ? r : this.left, null != i ? i : this.right);\n    }\n    isEmpty() {\n        return !1;\n    }\n    // Traverses the tree in key order and calls the specified action function\n    // for each node. If action returns true, traversal is aborted.\n    // Returns the first truthy value returned by action, or the last falsey\n    // value returned by action.\n    inorderTraversal(e) {\n        return this.left.inorderTraversal(e) || e(this.key, this.value) || this.right.inorderTraversal(e);\n    }\n    // Traverses the tree in reverse key order and calls the specified action\n    // function for each node. If action returns true, traversal is aborted.\n    // Returns the first truthy value returned by action, or the last falsey\n    // value returned by action.\n    reverseTraversal(e) {\n        return this.right.reverseTraversal(e) || e(this.key, this.value) || this.left.reverseTraversal(e);\n    }\n    // Returns the minimum node in the tree.\n    min() {\n        return this.left.isEmpty() ? this : this.left.min();\n    }\n    // Returns the maximum key in the tree.\n    minKey() {\n        return this.min().key;\n    }\n    // Returns the maximum key in the tree.\n    maxKey() {\n        return this.right.isEmpty() ? this.key : this.right.maxKey();\n    }\n    // Returns new tree, with the key/value added.\n    insert(e, t, n) {\n        let r = this;\n        const i = n(e, r.key);\n        return r = i < 0 ? r.copy(null, null, null, r.left.insert(e, t, n), null) : 0 === i ? r.copy(null, t, null, null, null) : r.copy(null, null, null, null, r.right.insert(e, t, n)), \n        r.fixUp();\n    }\n    removeMin() {\n        if (this.left.isEmpty()) return LLRBNode.EMPTY;\n        let e = this;\n        return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), e = e.copy(null, null, null, e.left.removeMin(), null), \n        e.fixUp();\n    }\n    // Returns new tree, with the specified item removed.\n    remove(e, t) {\n        let n, r = this;\n        if (t(e, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()), \n        r = r.copy(null, null, null, r.left.remove(e, t), null); else {\n            if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()), \n            0 === t(e, r.key)) {\n                if (r.right.isEmpty()) return LLRBNode.EMPTY;\n                n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin());\n            }\n            r = r.copy(null, null, null, null, r.right.remove(e, t));\n        }\n        return r.fixUp();\n    }\n    isRed() {\n        return this.color;\n    }\n    // Returns new tree after performing any needed rotations.\n    fixUp() {\n        let e = this;\n        return e.right.isRed() && !e.left.isRed() && (e = e.rotateLeft()), e.left.isRed() && e.left.left.isRed() && (e = e.rotateRight()), \n        e.left.isRed() && e.right.isRed() && (e = e.colorFlip()), e;\n    }\n    moveRedLeft() {\n        let e = this.colorFlip();\n        return e.right.left.isRed() && (e = e.copy(null, null, null, null, e.right.rotateRight()), \n        e = e.rotateLeft(), e = e.colorFlip()), e;\n    }\n    moveRedRight() {\n        let e = this.colorFlip();\n        return e.left.left.isRed() && (e = e.rotateRight(), e = e.colorFlip()), e;\n    }\n    rotateLeft() {\n        const e = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n        return this.right.copy(null, null, this.color, e, null);\n    }\n    rotateRight() {\n        const e = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n        return this.left.copy(null, null, this.color, null, e);\n    }\n    colorFlip() {\n        const e = this.left.copy(null, null, !this.left.color, null, null), t = this.right.copy(null, null, !this.right.color, null, null);\n        return this.copy(null, null, !this.color, e, t);\n    }\n    // For testing.\n    checkMaxDepth() {\n        const e = this.check();\n        return Math.pow(2, e) <= this.size + 1;\n    }\n    // In a balanced RB tree, the black-depth (number of black nodes) from root to\n    // leaves is equal on both sides.  This function verifies that or asserts.\n    check() {\n        if (this.isRed() && this.left.isRed()) throw fail();\n        if (this.right.isRed()) throw fail();\n        const e = this.left.check();\n        if (e !== this.right.check()) throw fail();\n        return e + (this.isRed() ? 0 : 1);\n    }\n}\n\n // end LLRBNode\n// Empty node is shared between all LLRB trees.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nLLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1;\n\n// end LLRBEmptyNode\nLLRBNode.EMPTY = new \n// Represents an empty node (a leaf node in the Red-Black Tree).\nclass LLRBEmptyNode {\n    constructor() {\n        this.size = 0;\n    }\n    get key() {\n        throw fail();\n    }\n    get value() {\n        throw fail();\n    }\n    get color() {\n        throw fail();\n    }\n    get left() {\n        throw fail();\n    }\n    get right() {\n        throw fail();\n    }\n    // Returns a copy of the current node.\n    copy(e, t, n, r, i) {\n        return this;\n    }\n    // Returns a copy of the tree, with the specified key/value added.\n    insert(e, t, n) {\n        return new LLRBNode(e, t);\n    }\n    // Returns a copy of the tree, with the specified key removed.\n    remove(e, t) {\n        return this;\n    }\n    isEmpty() {\n        return !0;\n    }\n    inorderTraversal(e) {\n        return !1;\n    }\n    reverseTraversal(e) {\n        return !1;\n    }\n    minKey() {\n        return null;\n    }\n    maxKey() {\n        return null;\n    }\n    isRed() {\n        return !1;\n    }\n    // For testing.\n    checkMaxDepth() {\n        return !0;\n    }\n    check() {\n        return 0;\n    }\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nclass SortedSet {\n    constructor(e) {\n        this.comparator = e, this.data = new SortedMap(this.comparator);\n    }\n    has(e) {\n        return null !== this.data.get(e);\n    }\n    first() {\n        return this.data.minKey();\n    }\n    last() {\n        return this.data.maxKey();\n    }\n    get size() {\n        return this.data.size;\n    }\n    indexOf(e) {\n        return this.data.indexOf(e);\n    }\n    /** Iterates elements in order defined by \"comparator\" */    forEach(e) {\n        this.data.inorderTraversal(((t, n) => (e(t), !1)));\n    }\n    /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */    forEachInRange(e, t) {\n        const n = this.data.getIteratorFrom(e[0]);\n        for (;n.hasNext(); ) {\n            const r = n.getNext();\n            if (this.comparator(r.key, e[1]) >= 0) return;\n            t(r.key);\n        }\n    }\n    /**\n     * Iterates over `elem`s such that: start &lt;= elem until false is returned.\n     */    forEachWhile(e, t) {\n        let n;\n        for (n = void 0 !== t ? this.data.getIteratorFrom(t) : this.data.getIterator(); n.hasNext(); ) {\n            if (!e(n.getNext().key)) return;\n        }\n    }\n    /** Finds the least element greater than or equal to `elem`. */    firstAfterOrEqual(e) {\n        const t = this.data.getIteratorFrom(e);\n        return t.hasNext() ? t.getNext().key : null;\n    }\n    getIterator() {\n        return new SortedSetIterator(this.data.getIterator());\n    }\n    getIteratorFrom(e) {\n        return new SortedSetIterator(this.data.getIteratorFrom(e));\n    }\n    /** Inserts or updates an element */    add(e) {\n        return this.copy(this.data.remove(e).insert(e, !0));\n    }\n    /** Deletes an element */    delete(e) {\n        return this.has(e) ? this.copy(this.data.remove(e)) : this;\n    }\n    isEmpty() {\n        return this.data.isEmpty();\n    }\n    unionWith(e) {\n        let t = this;\n        // Make sure `result` always refers to the larger one of the two sets.\n                return t.size < e.size && (t = e, e = this), e.forEach((e => {\n            t = t.add(e);\n        })), t;\n    }\n    isEqual(e) {\n        if (!(e instanceof SortedSet)) return !1;\n        if (this.size !== e.size) return !1;\n        const t = this.data.getIterator(), n = e.data.getIterator();\n        for (;t.hasNext(); ) {\n            const e = t.getNext().key, r = n.getNext().key;\n            if (0 !== this.comparator(e, r)) return !1;\n        }\n        return !0;\n    }\n    toArray() {\n        const e = [];\n        return this.forEach((t => {\n            e.push(t);\n        })), e;\n    }\n    toString() {\n        const e = [];\n        return this.forEach((t => e.push(t))), \"SortedSet(\" + e.toString() + \")\";\n    }\n    copy(e) {\n        const t = new SortedSet(this.comparator);\n        return t.data = e, t;\n    }\n}\n\nclass SortedSetIterator {\n    constructor(e) {\n        this.iter = e;\n    }\n    getNext() {\n        return this.iter.getNext().key;\n    }\n    hasNext() {\n        return this.iter.hasNext();\n    }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction __PRIVATE_advanceIterator(e) {\n    return e.hasNext() ? e.getNext() : void 0;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n *   foo - Overwrites foo entirely with the provided value. If foo is not\n *         present in the companion ObjectValue, the field is deleted.\n *   foo.bar - Overwrites only the field bar of the object foo.\n *             If foo is not an object, foo is replaced with an object\n *             containing foo\n */ class FieldMask {\n    constructor(e) {\n        this.fields = e, \n        // TODO(dimond): validation of FieldMask\n        // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n        e.sort(FieldPath$1.comparator);\n    }\n    static empty() {\n        return new FieldMask([]);\n    }\n    /**\n     * Returns a new FieldMask object that is the result of adding all the given\n     * fields paths to this field mask.\n     */    unionWith(e) {\n        let t = new SortedSet(FieldPath$1.comparator);\n        for (const e of this.fields) t = t.add(e);\n        for (const n of e) t = t.add(n);\n        return new FieldMask(t.toArray());\n    }\n    /**\n     * Verifies that `fieldPath` is included by at least one field in this field\n     * mask.\n     *\n     * This is an O(n) operation, where `n` is the size of the field mask.\n     */    covers(e) {\n        for (const t of this.fields) if (t.isPrefixOf(e)) return !0;\n        return !1;\n    }\n    isEqual(e) {\n        return __PRIVATE_arrayEquals(this.fields, e.fields, ((e, t) => e.isEqual(t)));\n    }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An error encountered while decoding base64 string.\n */ class __PRIVATE_Base64DecodeError extends Error {\n    constructor() {\n        super(...arguments), this.name = \"Base64DecodeError\";\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Converts a Base64 encoded string to a binary string. */\n/** True if and only if the Base64 conversion functions are available. */\nfunction __PRIVATE_isBase64Available() {\n    return \"undefined\" != typeof atob;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */ class ByteString {\n    constructor(e) {\n        this.binaryString = e;\n    }\n    static fromBase64String(e) {\n        const t = function __PRIVATE_decodeBase64(e) {\n            try {\n                return atob(e);\n            } catch (e) {\n                // Check that `DOMException` is defined before using it to avoid\n                // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n                // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n                throw \"undefined\" != typeof DOMException && e instanceof DOMException ? new __PRIVATE_Base64DecodeError(\"Invalid base64 string: \" + e) : e;\n            }\n        }\n        /** Converts a binary string to a Base64 encoded string. */ (e);\n        return new ByteString(t);\n    }\n    static fromUint8Array(e) {\n        // TODO(indexing); Remove the copy of the byte string here as this method\n        // is frequently called during indexing.\n        const t = \n        /**\n * Helper function to convert an Uint8array to a binary string.\n */\n        function __PRIVATE_binaryStringFromUint8Array(e) {\n            let t = \"\";\n            for (let n = 0; n < e.length; ++n) t += String.fromCharCode(e[n]);\n            return t;\n        }\n        /**\n * Helper function to convert a binary string to an Uint8Array.\n */ (e);\n        return new ByteString(t);\n    }\n    [Symbol.iterator]() {\n        let e = 0;\n        return {\n            next: () => e < this.binaryString.length ? {\n                value: this.binaryString.charCodeAt(e++),\n                done: !1\n            } : {\n                value: void 0,\n                done: !0\n            }\n        };\n    }\n    toBase64() {\n        return function __PRIVATE_encodeBase64(e) {\n            return btoa(e);\n        }(this.binaryString);\n    }\n    toUint8Array() {\n        return function __PRIVATE_uint8ArrayFromBinaryString(e) {\n            const t = new Uint8Array(e.length);\n            for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n);\n            return t;\n        }\n        /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n        // A RegExp matching ISO 8601 UTC timestamps with optional fraction.\n        (this.binaryString);\n    }\n    approximateByteSize() {\n        return 2 * this.binaryString.length;\n    }\n    compareTo(e) {\n        return __PRIVATE_primitiveComparator(this.binaryString, e.binaryString);\n    }\n    isEqual(e) {\n        return this.binaryString === e.binaryString;\n    }\n}\n\nByteString.EMPTY_BYTE_STRING = new ByteString(\"\");\n\nconst te = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */ function __PRIVATE_normalizeTimestamp(e) {\n    // The json interface (for the browser) will return an iso timestamp string,\n    // while the proto js library (for node) will return a\n    // google.protobuf.Timestamp instance.\n    if (__PRIVATE_hardAssert(!!e), \"string\" == typeof e) {\n        // The date string can have higher precision (nanos) than the Date class\n        // (millis), so we do some custom parsing here.\n        // Parse the nanos right out of the string.\n        let t = 0;\n        const n = te.exec(e);\n        if (__PRIVATE_hardAssert(!!n), n[1]) {\n            // Pad the fraction out to 9 digits (nanos).\n            let e = n[1];\n            e = (e + \"000000000\").substr(0, 9), t = Number(e);\n        }\n        // Parse the date to get the seconds.\n                const r = new Date(e);\n        return {\n            seconds: Math.floor(r.getTime() / 1e3),\n            nanos: t\n        };\n    }\n    return {\n        seconds: __PRIVATE_normalizeNumber(e.seconds),\n        nanos: __PRIVATE_normalizeNumber(e.nanos)\n    };\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */ function __PRIVATE_normalizeNumber(e) {\n    // TODO(bjornick): Handle int64 greater than 53 bits.\n    return \"number\" == typeof e ? e : \"string\" == typeof e ? Number(e) : 0;\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(e) {\n    return \"string\" == typeof e ? ByteString.fromBase64String(e) : ByteString.fromUint8Array(e);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n *   transform. They can only exist in the local view of a document. Therefore\n *   they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n *   evaluate to `null`. This behavior can be configured by passing custom\n *   FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n *   localWriteTime.\n */ function __PRIVATE_isServerTimestamp(e) {\n    var t, n;\n    return \"server_timestamp\" === (null === (n = ((null === (t = null == e ? void 0 : e.mapValue) || void 0 === t ? void 0 : t.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nfunction __PRIVATE_getPreviousValue(e) {\n    const t = e.mapValue.fields.__previous_value__;\n    return __PRIVATE_isServerTimestamp(t) ? __PRIVATE_getPreviousValue(t) : t;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */ function __PRIVATE_getLocalWriteTime(e) {\n    const t = __PRIVATE_normalizeTimestamp(e.mapValue.fields.__local_write_time__.timestampValue);\n    return new Timestamp(t.seconds, t.nanos);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class DatabaseInfo {\n    /**\n     * Constructs a DatabaseInfo using the provided host, databaseId and\n     * persistenceKey.\n     *\n     * @param databaseId - The database to use.\n     * @param appId - The Firebase App Id.\n     * @param persistenceKey - A unique identifier for this Firestore's local\n     * storage (used in conjunction with the databaseId).\n     * @param host - The Firestore backend host to connect to.\n     * @param ssl - Whether to use SSL when connecting.\n     * @param forceLongPolling - Whether to use the forceLongPolling option\n     * when using WebChannel as the network transport.\n     * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n     * option when using WebChannel as the network transport.\n     * @param longPollingOptions Options that configure long-polling.\n     * @param useFetchStreams Whether to use the Fetch API instead of\n     * XMLHTTPRequest\n     */\n    constructor(e, t, n, r, i, s, o, _, a) {\n        this.databaseId = e, this.appId = t, this.persistenceKey = n, this.host = r, this.ssl = i, \n        this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = _, \n        this.useFetchStreams = a;\n    }\n}\n\n/** The default database name for a project. */\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nclass DatabaseId {\n    constructor(e, t) {\n        this.projectId = e, this.database = t || \"(default)\";\n    }\n    static empty() {\n        return new DatabaseId(\"\", \"\");\n    }\n    get isDefaultDatabase() {\n        return \"(default)\" === this.database;\n    }\n    isEqual(e) {\n        return e instanceof DatabaseId && e.projectId === this.projectId && e.database === this.database;\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst ne = {\n    mapValue: {\n        fields: {\n            __type__: {\n                stringValue: \"__max__\"\n            }\n        }\n    }\n}, re = {\n    nullValue: \"NULL_VALUE\"\n};\n\n/** Extracts the backend's type order for the provided value. */\nfunction __PRIVATE_typeOrder(e) {\n    return \"nullValue\" in e ? 0 /* TypeOrder.NullValue */ : \"booleanValue\" in e ? 1 /* TypeOrder.BooleanValue */ : \"integerValue\" in e || \"doubleValue\" in e ? 2 /* TypeOrder.NumberValue */ : \"timestampValue\" in e ? 3 /* TypeOrder.TimestampValue */ : \"stringValue\" in e ? 5 /* TypeOrder.StringValue */ : \"bytesValue\" in e ? 6 /* TypeOrder.BlobValue */ : \"referenceValue\" in e ? 7 /* TypeOrder.RefValue */ : \"geoPointValue\" in e ? 8 /* TypeOrder.GeoPointValue */ : \"arrayValue\" in e ? 9 /* TypeOrder.ArrayValue */ : \"mapValue\" in e ? __PRIVATE_isServerTimestamp(e) ? 4 /* TypeOrder.ServerTimestampValue */ : __PRIVATE_isMaxValue(e) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : fail();\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(e, t) {\n    if (e === t) return !0;\n    const n = __PRIVATE_typeOrder(e);\n    if (n !== __PRIVATE_typeOrder(t)) return !1;\n    switch (n) {\n      case 0 /* TypeOrder.NullValue */ :\n      case 9007199254740991 /* TypeOrder.MaxValue */ :\n        return !0;\n\n      case 1 /* TypeOrder.BooleanValue */ :\n        return e.booleanValue === t.booleanValue;\n\n      case 4 /* TypeOrder.ServerTimestampValue */ :\n        return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(t));\n\n      case 3 /* TypeOrder.TimestampValue */ :\n        return function __PRIVATE_timestampEquals(e, t) {\n            if (\"string\" == typeof e.timestampValue && \"string\" == typeof t.timestampValue && e.timestampValue.length === t.timestampValue.length) \n            // Use string equality for ISO 8601 timestamps\n            return e.timestampValue === t.timestampValue;\n            const n = __PRIVATE_normalizeTimestamp(e.timestampValue), r = __PRIVATE_normalizeTimestamp(t.timestampValue);\n            return n.seconds === r.seconds && n.nanos === r.nanos;\n        }(e, t);\n\n      case 5 /* TypeOrder.StringValue */ :\n        return e.stringValue === t.stringValue;\n\n      case 6 /* TypeOrder.BlobValue */ :\n        return function __PRIVATE_blobEquals(e, t) {\n            return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(t.bytesValue));\n        }(e, t);\n\n      case 7 /* TypeOrder.RefValue */ :\n        return e.referenceValue === t.referenceValue;\n\n      case 8 /* TypeOrder.GeoPointValue */ :\n        return function __PRIVATE_geoPointEquals(e, t) {\n            return __PRIVATE_normalizeNumber(e.geoPointValue.latitude) === __PRIVATE_normalizeNumber(t.geoPointValue.latitude) && __PRIVATE_normalizeNumber(e.geoPointValue.longitude) === __PRIVATE_normalizeNumber(t.geoPointValue.longitude);\n        }(e, t);\n\n      case 2 /* TypeOrder.NumberValue */ :\n        return function __PRIVATE_numberEquals(e, t) {\n            if (\"integerValue\" in e && \"integerValue\" in t) return __PRIVATE_normalizeNumber(e.integerValue) === __PRIVATE_normalizeNumber(t.integerValue);\n            if (\"doubleValue\" in e && \"doubleValue\" in t) {\n                const n = __PRIVATE_normalizeNumber(e.doubleValue), r = __PRIVATE_normalizeNumber(t.doubleValue);\n                return n === r ? __PRIVATE_isNegativeZero(n) === __PRIVATE_isNegativeZero(r) : isNaN(n) && isNaN(r);\n            }\n            return !1;\n        }(e, t);\n\n      case 9 /* TypeOrder.ArrayValue */ :\n        return __PRIVATE_arrayEquals(e.arrayValue.values || [], t.arrayValue.values || [], __PRIVATE_valueEquals);\n\n      case 10 /* TypeOrder.ObjectValue */ :\n        return function __PRIVATE_objectEquals(e, t) {\n            const n = e.mapValue.fields || {}, r = t.mapValue.fields || {};\n            if (__PRIVATE_objectSize(n) !== __PRIVATE_objectSize(r)) return !1;\n            for (const e in n) if (n.hasOwnProperty(e) && (void 0 === r[e] || !__PRIVATE_valueEquals(n[e], r[e]))) return !1;\n            return !0;\n        }\n        /** Returns true if the ArrayValue contains the specified element. */ (e, t);\n\n      default:\n        return fail();\n    }\n}\n\nfunction __PRIVATE_arrayValueContains(e, t) {\n    return void 0 !== (e.values || []).find((e => __PRIVATE_valueEquals(e, t)));\n}\n\nfunction __PRIVATE_valueCompare(e, t) {\n    if (e === t) return 0;\n    const n = __PRIVATE_typeOrder(e), r = __PRIVATE_typeOrder(t);\n    if (n !== r) return __PRIVATE_primitiveComparator(n, r);\n    switch (n) {\n      case 0 /* TypeOrder.NullValue */ :\n      case 9007199254740991 /* TypeOrder.MaxValue */ :\n        return 0;\n\n      case 1 /* TypeOrder.BooleanValue */ :\n        return __PRIVATE_primitiveComparator(e.booleanValue, t.booleanValue);\n\n      case 2 /* TypeOrder.NumberValue */ :\n        return function __PRIVATE_compareNumbers(e, t) {\n            const n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue), r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue);\n            return n < r ? -1 : n > r ? 1 : n === r ? 0 : \n            // one or both are NaN.\n            isNaN(n) ? isNaN(r) ? 0 : -1 : 1;\n        }(e, t);\n\n      case 3 /* TypeOrder.TimestampValue */ :\n        return __PRIVATE_compareTimestamps(e.timestampValue, t.timestampValue);\n\n      case 4 /* TypeOrder.ServerTimestampValue */ :\n        return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e), __PRIVATE_getLocalWriteTime(t));\n\n      case 5 /* TypeOrder.StringValue */ :\n        return __PRIVATE_primitiveComparator(e.stringValue, t.stringValue);\n\n      case 6 /* TypeOrder.BlobValue */ :\n        return function __PRIVATE_compareBlobs(e, t) {\n            const n = __PRIVATE_normalizeByteString(e), r = __PRIVATE_normalizeByteString(t);\n            return n.compareTo(r);\n        }(e.bytesValue, t.bytesValue);\n\n      case 7 /* TypeOrder.RefValue */ :\n        return function __PRIVATE_compareReferences(e, t) {\n            const n = e.split(\"/\"), r = t.split(\"/\");\n            for (let e = 0; e < n.length && e < r.length; e++) {\n                const t = __PRIVATE_primitiveComparator(n[e], r[e]);\n                if (0 !== t) return t;\n            }\n            return __PRIVATE_primitiveComparator(n.length, r.length);\n        }(e.referenceValue, t.referenceValue);\n\n      case 8 /* TypeOrder.GeoPointValue */ :\n        return function __PRIVATE_compareGeoPoints(e, t) {\n            const n = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(t.latitude));\n            if (0 !== n) return n;\n            return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude), __PRIVATE_normalizeNumber(t.longitude));\n        }(e.geoPointValue, t.geoPointValue);\n\n      case 9 /* TypeOrder.ArrayValue */ :\n        return function __PRIVATE_compareArrays(e, t) {\n            const n = e.values || [], r = t.values || [];\n            for (let e = 0; e < n.length && e < r.length; ++e) {\n                const t = __PRIVATE_valueCompare(n[e], r[e]);\n                if (t) return t;\n            }\n            return __PRIVATE_primitiveComparator(n.length, r.length);\n        }(e.arrayValue, t.arrayValue);\n\n      case 10 /* TypeOrder.ObjectValue */ :\n        return function __PRIVATE_compareMaps(e, t) {\n            if (e === ne.mapValue && t === ne.mapValue) return 0;\n            if (e === ne.mapValue) return 1;\n            if (t === ne.mapValue) return -1;\n            const n = e.fields || {}, r = Object.keys(n), i = t.fields || {}, s = Object.keys(i);\n            // Even though MapValues are likely sorted correctly based on their insertion\n            // order (e.g. when received from the backend), local modifications can bring\n            // elements out of order. We need to re-sort the elements to ensure that\n            // canonical IDs are independent of insertion order.\n            r.sort(), s.sort();\n            for (let e = 0; e < r.length && e < s.length; ++e) {\n                const t = __PRIVATE_primitiveComparator(r[e], s[e]);\n                if (0 !== t) return t;\n                const o = __PRIVATE_valueCompare(n[r[e]], i[s[e]]);\n                if (0 !== o) return o;\n            }\n            return __PRIVATE_primitiveComparator(r.length, s.length);\n        }\n        /**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */ (e.mapValue, t.mapValue);\n\n      default:\n        throw fail();\n    }\n}\n\nfunction __PRIVATE_compareTimestamps(e, t) {\n    if (\"string\" == typeof e && \"string\" == typeof t && e.length === t.length) return __PRIVATE_primitiveComparator(e, t);\n    const n = __PRIVATE_normalizeTimestamp(e), r = __PRIVATE_normalizeTimestamp(t), i = __PRIVATE_primitiveComparator(n.seconds, r.seconds);\n    return 0 !== i ? i : __PRIVATE_primitiveComparator(n.nanos, r.nanos);\n}\n\nfunction canonicalId(e) {\n    return __PRIVATE_canonifyValue(e);\n}\n\nfunction __PRIVATE_canonifyValue(e) {\n    return \"nullValue\" in e ? \"null\" : \"booleanValue\" in e ? \"\" + e.booleanValue : \"integerValue\" in e ? \"\" + e.integerValue : \"doubleValue\" in e ? \"\" + e.doubleValue : \"timestampValue\" in e ? function __PRIVATE_canonifyTimestamp(e) {\n        const t = __PRIVATE_normalizeTimestamp(e);\n        return `time(${t.seconds},${t.nanos})`;\n    }(e.timestampValue) : \"stringValue\" in e ? e.stringValue : \"bytesValue\" in e ? function __PRIVATE_canonifyByteString(e) {\n        return __PRIVATE_normalizeByteString(e).toBase64();\n    }(e.bytesValue) : \"referenceValue\" in e ? function __PRIVATE_canonifyReference(e) {\n        return DocumentKey.fromName(e).toString();\n    }(e.referenceValue) : \"geoPointValue\" in e ? function __PRIVATE_canonifyGeoPoint(e) {\n        return `geo(${e.latitude},${e.longitude})`;\n    }(e.geoPointValue) : \"arrayValue\" in e ? function __PRIVATE_canonifyArray(e) {\n        let t = \"[\", n = !0;\n        for (const r of e.values || []) n ? n = !1 : t += \",\", t += __PRIVATE_canonifyValue(r);\n        return t + \"]\";\n    }\n    /**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */ (e.arrayValue) : \"mapValue\" in e ? function __PRIVATE_canonifyMap(e) {\n        // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n        // matching canonical IDs for identical maps, we need to sort the keys.\n        const t = Object.keys(e.fields || {}).sort();\n        let n = \"{\", r = !0;\n        for (const i of t) r ? r = !1 : n += \",\", n += `${i}:${__PRIVATE_canonifyValue(e.fields[i])}`;\n        return n + \"}\";\n    }(e.mapValue) : fail();\n}\n\nfunction __PRIVATE_estimateByteSize(e) {\n    switch (__PRIVATE_typeOrder(e)) {\n      case 0 /* TypeOrder.NullValue */ :\n      case 1 /* TypeOrder.BooleanValue */ :\n        return 4;\n\n      case 2 /* TypeOrder.NumberValue */ :\n        return 8;\n\n      case 3 /* TypeOrder.TimestampValue */ :\n      case 8 /* TypeOrder.GeoPointValue */ :\n        // GeoPoints are made up of two distinct numbers (latitude + longitude)\n        return 16;\n\n      case 4 /* TypeOrder.ServerTimestampValue */ :\n        const t = __PRIVATE_getPreviousValue(e);\n        return t ? 16 + __PRIVATE_estimateByteSize(t) : 16;\n\n      case 5 /* TypeOrder.StringValue */ :\n        // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n        // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n        // integer values\"\n        return 2 * e.stringValue.length;\n\n      case 6 /* TypeOrder.BlobValue */ :\n        return __PRIVATE_normalizeByteString(e.bytesValue).approximateByteSize();\n\n      case 7 /* TypeOrder.RefValue */ :\n        return e.referenceValue.length;\n\n      case 9 /* TypeOrder.ArrayValue */ :\n        return function __PRIVATE_estimateArrayByteSize(e) {\n            return (e.values || []).reduce(((e, t) => e + __PRIVATE_estimateByteSize(t)), 0);\n        }\n        /** Returns a reference value for the provided database and key. */ (e.arrayValue);\n\n      case 10 /* TypeOrder.ObjectValue */ :\n        return function __PRIVATE_estimateMapByteSize(e) {\n            let t = 0;\n            return forEach(e.fields, ((e, n) => {\n                t += e.length + __PRIVATE_estimateByteSize(n);\n            })), t;\n        }(e.mapValue);\n\n      default:\n        throw fail();\n    }\n}\n\nfunction __PRIVATE_refValue(e, t) {\n    return {\n        referenceValue: `projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`\n    };\n}\n\n/** Returns true if `value` is an IntegerValue . */ function isInteger(e) {\n    return !!e && \"integerValue\" in e;\n}\n\n/** Returns true if `value` is a DoubleValue. */\n/** Returns true if `value` is an ArrayValue. */\nfunction isArray(e) {\n    return !!e && \"arrayValue\" in e;\n}\n\n/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(e) {\n    return !!e && \"nullValue\" in e;\n}\n\n/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(e) {\n    return !!e && \"doubleValue\" in e && isNaN(Number(e.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(e) {\n    return !!e && \"mapValue\" in e;\n}\n\n/** Creates a deep copy of `source`. */ function __PRIVATE_deepClone(e) {\n    if (e.geoPointValue) return {\n        geoPointValue: Object.assign({}, e.geoPointValue)\n    };\n    if (e.timestampValue && \"object\" == typeof e.timestampValue) return {\n        timestampValue: Object.assign({}, e.timestampValue)\n    };\n    if (e.mapValue) {\n        const t = {\n            mapValue: {\n                fields: {}\n            }\n        };\n        return forEach(e.mapValue.fields, ((e, n) => t.mapValue.fields[e] = __PRIVATE_deepClone(n))), \n        t;\n    }\n    if (e.arrayValue) {\n        const t = {\n            arrayValue: {\n                values: []\n            }\n        };\n        for (let n = 0; n < (e.arrayValue.values || []).length; ++n) t.arrayValue.values[n] = __PRIVATE_deepClone(e.arrayValue.values[n]);\n        return t;\n    }\n    return Object.assign({}, e);\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function __PRIVATE_isMaxValue(e) {\n    return \"__max__\" === (((e.mapValue || {}).fields || {}).__type__ || {}).stringValue;\n}\n\n/** Returns the lowest value for the given value type (inclusive). */ function __PRIVATE_valuesGetLowerBound(e) {\n    return \"nullValue\" in e ? re : \"booleanValue\" in e ? {\n        booleanValue: !1\n    } : \"integerValue\" in e || \"doubleValue\" in e ? {\n        doubleValue: NaN\n    } : \"timestampValue\" in e ? {\n        timestampValue: {\n            seconds: Number.MIN_SAFE_INTEGER\n        }\n    } : \"stringValue\" in e ? {\n        stringValue: \"\"\n    } : \"bytesValue\" in e ? {\n        bytesValue: \"\"\n    } : \"referenceValue\" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : \"geoPointValue\" in e ? {\n        geoPointValue: {\n            latitude: -90,\n            longitude: -180\n        }\n    } : \"arrayValue\" in e ? {\n        arrayValue: {}\n    } : \"mapValue\" in e ? {\n        mapValue: {}\n    } : fail();\n}\n\n/** Returns the largest value for the given value type (exclusive). */ function __PRIVATE_valuesGetUpperBound(e) {\n    return \"nullValue\" in e ? {\n        booleanValue: !1\n    } : \"booleanValue\" in e ? {\n        doubleValue: NaN\n    } : \"integerValue\" in e || \"doubleValue\" in e ? {\n        timestampValue: {\n            seconds: Number.MIN_SAFE_INTEGER\n        }\n    } : \"timestampValue\" in e ? {\n        stringValue: \"\"\n    } : \"stringValue\" in e ? {\n        bytesValue: \"\"\n    } : \"bytesValue\" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : \"referenceValue\" in e ? {\n        geoPointValue: {\n            latitude: -90,\n            longitude: -180\n        }\n    } : \"geoPointValue\" in e ? {\n        arrayValue: {}\n    } : \"arrayValue\" in e ? {\n        mapValue: {}\n    } : \"mapValue\" in e ? ne : fail();\n}\n\nfunction __PRIVATE_lowerBoundCompare(e, t) {\n    const n = __PRIVATE_valueCompare(e.value, t.value);\n    return 0 !== n ? n : e.inclusive && !t.inclusive ? -1 : !e.inclusive && t.inclusive ? 1 : 0;\n}\n\nfunction __PRIVATE_upperBoundCompare(e, t) {\n    const n = __PRIVATE_valueCompare(e.value, t.value);\n    return 0 !== n ? n : e.inclusive && !t.inclusive ? 1 : !e.inclusive && t.inclusive ? -1 : 0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */ class ObjectValue {\n    constructor(e) {\n        this.value = e;\n    }\n    static empty() {\n        return new ObjectValue({\n            mapValue: {}\n        });\n    }\n    /**\n     * Returns the value at the given path or null.\n     *\n     * @param path - the path to search\n     * @returns The value at the path or null if the path is not set.\n     */    field(e) {\n        if (e.isEmpty()) return this.value;\n        {\n            let t = this.value;\n            for (let n = 0; n < e.length - 1; ++n) if (t = (t.mapValue.fields || {})[e.get(n)], \n            !__PRIVATE_isMapValue(t)) return null;\n            return t = (t.mapValue.fields || {})[e.lastSegment()], t || null;\n        }\n    }\n    /**\n     * Sets the field to the provided value.\n     *\n     * @param path - The field path to set.\n     * @param value - The value to set.\n     */    set(e, t) {\n        this.getFieldsMap(e.popLast())[e.lastSegment()] = __PRIVATE_deepClone(t);\n    }\n    /**\n     * Sets the provided fields to the provided values.\n     *\n     * @param data - A map of fields to values (or null for deletes).\n     */    setAll(e) {\n        let t = FieldPath$1.emptyPath(), n = {}, r = [];\n        e.forEach(((e, i) => {\n            if (!t.isImmediateParentOf(i)) {\n                // Insert the accumulated changes at this parent location\n                const e = this.getFieldsMap(t);\n                this.applyChanges(e, n, r), n = {}, r = [], t = i.popLast();\n            }\n            e ? n[i.lastSegment()] = __PRIVATE_deepClone(e) : r.push(i.lastSegment());\n        }));\n        const i = this.getFieldsMap(t);\n        this.applyChanges(i, n, r);\n    }\n    /**\n     * Removes the field at the specified path. If there is no field at the\n     * specified path, nothing is changed.\n     *\n     * @param path - The field path to remove.\n     */    delete(e) {\n        const t = this.field(e.popLast());\n        __PRIVATE_isMapValue(t) && t.mapValue.fields && delete t.mapValue.fields[e.lastSegment()];\n    }\n    isEqual(e) {\n        return __PRIVATE_valueEquals(this.value, e.value);\n    }\n    /**\n     * Returns the map that contains the leaf element of `path`. If the parent\n     * entry does not yet exist, or if it is not a map, a new map will be created.\n     */    getFieldsMap(e) {\n        let t = this.value;\n        t.mapValue.fields || (t.mapValue = {\n            fields: {}\n        });\n        for (let n = 0; n < e.length; ++n) {\n            let r = t.mapValue.fields[e.get(n)];\n            __PRIVATE_isMapValue(r) && r.mapValue.fields || (r = {\n                mapValue: {\n                    fields: {}\n                }\n            }, t.mapValue.fields[e.get(n)] = r), t = r;\n        }\n        return t.mapValue.fields;\n    }\n    /**\n     * Modifies `fieldsMap` by adding, replacing or deleting the specified\n     * entries.\n     */    applyChanges(e, t, n) {\n        forEach(t, ((t, n) => e[t] = n));\n        for (const t of n) delete e[t];\n    }\n    clone() {\n        return new ObjectValue(__PRIVATE_deepClone(this.value));\n    }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */ function __PRIVATE_extractFieldMask(e) {\n    const t = [];\n    return forEach(e.fields, ((e, n) => {\n        const r = new FieldPath$1([ e ]);\n        if (__PRIVATE_isMapValue(n)) {\n            const e = __PRIVATE_extractFieldMask(n.mapValue).fields;\n            if (0 === e.length) \n            // Preserve the empty map by adding it to the FieldMask.\n            t.push(r); else \n            // For nested and non-empty ObjectValues, add the FieldPath of the\n            // leaf nodes.\n            for (const n of e) t.push(r.child(n));\n        } else \n        // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n        // nodes.\n        t.push(r);\n    })), new FieldMask(t);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */ class MutableDocument {\n    constructor(e, t, n, r, i, s, o) {\n        this.key = e, this.documentType = t, this.version = n, this.readTime = r, this.createTime = i, \n        this.data = s, this.documentState = o;\n    }\n    /**\n     * Creates a document with no known version or data, but which can serve as\n     * base document for mutations.\n     */    static newInvalidDocument(e) {\n        return new MutableDocument(e, 0 /* DocumentType.INVALID */ , \n        /* version */ SnapshotVersion.min(), \n        /* readTime */ SnapshotVersion.min(), \n        /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);\n    }\n    /**\n     * Creates a new document that is known to exist with the given data at the\n     * given version.\n     */    static newFoundDocument(e, t, n, r) {\n        return new MutableDocument(e, 1 /* DocumentType.FOUND_DOCUMENT */ , \n        /* version */ t, \n        /* readTime */ SnapshotVersion.min(), \n        /* createTime */ n, r, 0 /* DocumentState.SYNCED */);\n    }\n    /** Creates a new document that is known to not exist at the given version. */    static newNoDocument(e, t) {\n        return new MutableDocument(e, 2 /* DocumentType.NO_DOCUMENT */ , \n        /* version */ t, \n        /* readTime */ SnapshotVersion.min(), \n        /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);\n    }\n    /**\n     * Creates a new document that is known to exist at the given version but\n     * whose data is not known (e.g. a document that was updated without a known\n     * base document).\n     */    static newUnknownDocument(e, t) {\n        return new MutableDocument(e, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n        /* version */ t, \n        /* readTime */ SnapshotVersion.min(), \n        /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);\n    }\n    /**\n     * Changes the document type to indicate that it exists and that its version\n     * and data are known.\n     */    convertToFoundDocument(e, t) {\n        // If a document is switching state from being an invalid or deleted\n        // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n        // update from Watch or due to applying a local set mutation on top\n        // of a deleted document, our best guess about its createTime would be the\n        // version at which the document transitioned to a FOUND_DOCUMENT.\n        return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = e), \n        this.version = e, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = t, \n        this.documentState = 0 /* DocumentState.SYNCED */ , this;\n    }\n    /**\n     * Changes the document type to indicate that it doesn't exist at the given\n     * version.\n     */    convertToNoDocument(e) {\n        return this.version = e, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , \n        this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , \n        this;\n    }\n    /**\n     * Changes the document type to indicate that it exists at a given version but\n     * that its data is not known (e.g. a document that was updated without a known\n     * base document).\n     */    convertToUnknownDocument(e) {\n        return this.version = e, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n        this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , \n        this;\n    }\n    setHasCommittedMutations() {\n        return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;\n    }\n    setHasLocalMutations() {\n        return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), \n        this;\n    }\n    setReadTime(e) {\n        return this.readTime = e, this;\n    }\n    get hasLocalMutations() {\n        return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;\n    }\n    get hasCommittedMutations() {\n        return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;\n    }\n    get hasPendingWrites() {\n        return this.hasLocalMutations || this.hasCommittedMutations;\n    }\n    isValidDocument() {\n        return 0 /* DocumentType.INVALID */ !== this.documentType;\n    }\n    isFoundDocument() {\n        return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;\n    }\n    isNoDocument() {\n        return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;\n    }\n    isUnknownDocument() {\n        return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;\n    }\n    isEqual(e) {\n        return e instanceof MutableDocument && this.key.isEqual(e.key) && this.version.isEqual(e.version) && this.documentType === e.documentType && this.documentState === e.documentState && this.data.isEqual(e.data);\n    }\n    mutableCopy() {\n        return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);\n    }\n    toString() {\n        return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;\n    }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nclass Bound {\n    constructor(e, t) {\n        this.position = e, this.inclusive = t;\n    }\n}\n\nfunction __PRIVATE_boundCompareToDocument(e, t, n) {\n    let r = 0;\n    for (let i = 0; i < e.position.length; i++) {\n        const s = t[i], o = e.position[i];\n        if (s.field.isKeyField()) r = DocumentKey.comparator(DocumentKey.fromName(o.referenceValue), n.key); else {\n            r = __PRIVATE_valueCompare(o, n.data.field(s.field));\n        }\n        if (\"desc\" /* Direction.DESCENDING */ === s.dir && (r *= -1), 0 !== r) break;\n    }\n    return r;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */ function __PRIVATE_boundEquals(e, t) {\n    if (null === e) return null === t;\n    if (null === t) return !1;\n    if (e.inclusive !== t.inclusive || e.position.length !== t.position.length) return !1;\n    for (let n = 0; n < e.position.length; n++) {\n        if (!__PRIVATE_valueEquals(e.position[n], t.position[n])) return !1;\n    }\n    return !0;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */ class OrderBy {\n    constructor(e, t = \"asc\" /* Direction.ASCENDING */) {\n        this.field = e, this.dir = t;\n    }\n}\n\nfunction __PRIVATE_orderByEquals(e, t) {\n    return e.dir === t.dir && e.field.isEqual(t.field);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Filter {}\n\nclass FieldFilter extends Filter {\n    constructor(e, t, n) {\n        super(), this.field = e, this.op = t, this.value = n;\n    }\n    /**\n     * Creates a filter based on the provided arguments.\n     */    static create(e, t, n) {\n        return e.isKeyField() ? \"in\" /* Operator.IN */ === t || \"not-in\" /* Operator.NOT_IN */ === t ? this.createKeyFieldInFilter(e, t, n) : new __PRIVATE_KeyFieldFilter(e, t, n) : \"array-contains\" /* Operator.ARRAY_CONTAINS */ === t ? new __PRIVATE_ArrayContainsFilter(e, n) : \"in\" /* Operator.IN */ === t ? new __PRIVATE_InFilter(e, n) : \"not-in\" /* Operator.NOT_IN */ === t ? new __PRIVATE_NotInFilter(e, n) : \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === t ? new __PRIVATE_ArrayContainsAnyFilter(e, n) : new FieldFilter(e, t, n);\n    }\n    static createKeyFieldInFilter(e, t, n) {\n        return \"in\" /* Operator.IN */ === t ? new __PRIVATE_KeyFieldInFilter(e, n) : new __PRIVATE_KeyFieldNotInFilter(e, n);\n    }\n    matches(e) {\n        const t = e.data.field(this.field);\n        // Types do not have to match in NOT_EQUAL filters.\n                return \"!=\" /* Operator.NOT_EQUAL */ === this.op ? null !== t && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)) : null !== t && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(t) && this.matchesComparison(__PRIVATE_valueCompare(t, this.value));\n        // Only compare types with matching backend order (such as double and int).\n        }\n    matchesComparison(e) {\n        switch (this.op) {\n          case \"<\" /* Operator.LESS_THAN */ :\n            return e < 0;\n\n          case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n            return e <= 0;\n\n          case \"==\" /* Operator.EQUAL */ :\n            return 0 === e;\n\n          case \"!=\" /* Operator.NOT_EQUAL */ :\n            return 0 !== e;\n\n          case \">\" /* Operator.GREATER_THAN */ :\n            return e > 0;\n\n          case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n            return e >= 0;\n\n          default:\n            return fail();\n        }\n    }\n    isInequality() {\n        return [ \"<\" /* Operator.LESS_THAN */ , \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ , \">\" /* Operator.GREATER_THAN */ , \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ , \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;\n    }\n    getFlattenedFilters() {\n        return [ this ];\n    }\n    getFilters() {\n        return [ this ];\n    }\n    getFirstInequalityField() {\n        return this.isInequality() ? this.field : null;\n    }\n}\n\nclass CompositeFilter extends Filter {\n    constructor(e, t) {\n        super(), this.filters = e, this.op = t, this.ce = null;\n    }\n    /**\n     * Creates a filter based on the provided arguments.\n     */    static create(e, t) {\n        return new CompositeFilter(e, t);\n    }\n    matches(e) {\n        return __PRIVATE_compositeFilterIsConjunction(this) ? void 0 === this.filters.find((t => !t.matches(e))) : void 0 !== this.filters.find((t => t.matches(e)));\n    }\n    getFlattenedFilters() {\n        return null !== this.ce || (this.ce = this.filters.reduce(((e, t) => e.concat(t.getFlattenedFilters())), [])), \n        this.ce;\n    }\n    // Returns a mutable copy of `this.filters`\n    getFilters() {\n        return Object.assign([], this.filters);\n    }\n    getFirstInequalityField() {\n        const e = this.le((e => e.isInequality()));\n        return null !== e ? e.field : null;\n    }\n    // Performs a depth-first search to find and return the first FieldFilter in the composite filter\n    // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the\n    // predicate.\n    le(e) {\n        for (const t of this.getFlattenedFilters()) if (e(t)) return t;\n        return null;\n    }\n}\n\nfunction __PRIVATE_compositeFilterIsConjunction(e) {\n    return \"and\" /* CompositeOperator.AND */ === e.op;\n}\n\nfunction __PRIVATE_compositeFilterIsDisjunction(e) {\n    return \"or\" /* CompositeOperator.OR */ === e.op;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */ function __PRIVATE_compositeFilterIsFlatConjunction(e) {\n    return __PRIVATE_compositeFilterIsFlat(e) && __PRIVATE_compositeFilterIsConjunction(e);\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */ function __PRIVATE_compositeFilterIsFlat(e) {\n    for (const t of e.filters) if (t instanceof CompositeFilter) return !1;\n    return !0;\n}\n\nfunction __PRIVATE_canonifyFilter(e) {\n    if (e instanceof FieldFilter) \n    // TODO(b/29183165): Technically, this won't be unique if two values have\n    // the same description, such as the int 3 and the string \"3\". So we should\n    // add the types in here somehow, too.\n    return e.field.canonicalString() + e.op.toString() + canonicalId(e.value);\n    if (__PRIVATE_compositeFilterIsFlatConjunction(e)) \n    // Older SDK versions use an implicit AND operation between their filters.\n    // In the new SDK versions, the developer may use an explicit AND filter.\n    // To stay consistent with the old usages, we add a special case to ensure\n    // the canonical ID for these two are the same. For example:\n    // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n    // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n    return e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(\",\");\n    {\n        // filter instanceof CompositeFilter\n        const t = e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(\",\");\n        return `${e.op}(${t})`;\n    }\n}\n\nfunction __PRIVATE_filterEquals(e, t) {\n    return e instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(e, t) {\n        return t instanceof FieldFilter && e.op === t.op && e.field.isEqual(t.field) && __PRIVATE_valueEquals(e.value, t.value);\n    }(e, t) : e instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(e, t) {\n        if (t instanceof CompositeFilter && e.op === t.op && e.filters.length === t.filters.length) {\n            return e.filters.reduce(((e, n, r) => e && __PRIVATE_filterEquals(n, t.filters[r])), !0);\n        }\n        return !1;\n    }\n    /**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */ (e, t) : void fail();\n}\n\nfunction __PRIVATE_compositeFilterWithAddedFilters(e, t) {\n    const n = e.filters.concat(t);\n    return CompositeFilter.create(n, e.op);\n}\n\n/** Returns a debug description for `filter`. */ function __PRIVATE_stringifyFilter(e) {\n    return e instanceof FieldFilter ? function __PRIVATE_stringifyFieldFilter(e) {\n        return `${e.field.canonicalString()} ${e.op} ${canonicalId(e.value)}`;\n    }\n    /** Filter that matches on key fields (i.e. '__name__'). */ (e) : e instanceof CompositeFilter ? function __PRIVATE_stringifyCompositeFilter(e) {\n        return e.op.toString() + \" {\" + e.getFilters().map(__PRIVATE_stringifyFilter).join(\" ,\") + \"}\";\n    }(e) : \"Filter\";\n}\n\nclass __PRIVATE_KeyFieldFilter extends FieldFilter {\n    constructor(e, t, n) {\n        super(e, t, n), this.key = DocumentKey.fromName(n.referenceValue);\n    }\n    matches(e) {\n        const t = DocumentKey.comparator(e.key, this.key);\n        return this.matchesComparison(t);\n    }\n}\n\n/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter {\n    constructor(e, t) {\n        super(e, \"in\" /* Operator.IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue(\"in\" /* Operator.IN */ , t);\n    }\n    matches(e) {\n        return this.keys.some((t => t.isEqual(e.key)));\n    }\n}\n\n/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter {\n    constructor(e, t) {\n        super(e, \"not-in\" /* Operator.NOT_IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue(\"not-in\" /* Operator.NOT_IN */ , t);\n    }\n    matches(e) {\n        return !this.keys.some((t => t.isEqual(e.key)));\n    }\n}\n\nfunction __PRIVATE_extractDocumentKeysFromArrayValue(e, t) {\n    var n;\n    return ((null === (n = t.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((e => DocumentKey.fromName(e.referenceValue)));\n}\n\n/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter {\n    constructor(e, t) {\n        super(e, \"array-contains\" /* Operator.ARRAY_CONTAINS */ , t);\n    }\n    matches(e) {\n        const t = e.data.field(this.field);\n        return isArray(t) && __PRIVATE_arrayValueContains(t.arrayValue, this.value);\n    }\n}\n\n/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter {\n    constructor(e, t) {\n        super(e, \"in\" /* Operator.IN */ , t);\n    }\n    matches(e) {\n        const t = e.data.field(this.field);\n        return null !== t && __PRIVATE_arrayValueContains(this.value.arrayValue, t);\n    }\n}\n\n/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter {\n    constructor(e, t) {\n        super(e, \"not-in\" /* Operator.NOT_IN */ , t);\n    }\n    matches(e) {\n        if (__PRIVATE_arrayValueContains(this.value.arrayValue, {\n            nullValue: \"NULL_VALUE\"\n        })) return !1;\n        const t = e.data.field(this.field);\n        return null !== t && !__PRIVATE_arrayValueContains(this.value.arrayValue, t);\n    }\n}\n\n/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter {\n    constructor(e, t) {\n        super(e, \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , t);\n    }\n    matches(e) {\n        const t = e.data.field(this.field);\n        return !(!isArray(t) || !t.arrayValue.values) && t.arrayValue.values.some((e => __PRIVATE_arrayValueContains(this.value.arrayValue, e)));\n    }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Visible for testing\nclass __PRIVATE_TargetImpl {\n    constructor(e, t = null, n = [], r = [], i = null, s = null, o = null) {\n        this.path = e, this.collectionGroup = t, this.orderBy = n, this.filters = r, this.limit = i, \n        this.startAt = s, this.endAt = o, this.he = null;\n    }\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */ function __PRIVATE_newTarget(e, t = null, n = [], r = [], i = null, s = null, o = null) {\n    return new __PRIVATE_TargetImpl(e, t, n, r, i, s, o);\n}\n\nfunction __PRIVATE_canonifyTarget(e) {\n    const t = __PRIVATE_debugCast(e);\n    if (null === t.he) {\n        let e = t.path.canonicalString();\n        null !== t.collectionGroup && (e += \"|cg:\" + t.collectionGroup), e += \"|f:\", e += t.filters.map((e => __PRIVATE_canonifyFilter(e))).join(\",\"), \n        e += \"|ob:\", e += t.orderBy.map((e => function __PRIVATE_canonifyOrderBy(e) {\n            // TODO(b/29183165): Make this collision robust.\n            return e.field.canonicalString() + e.dir;\n        }(e))).join(\",\"), __PRIVATE_isNullOrUndefined(t.limit) || (e += \"|l:\", e += t.limit), \n        t.startAt && (e += \"|lb:\", e += t.startAt.inclusive ? \"b:\" : \"a:\", e += t.startAt.position.map((e => canonicalId(e))).join(\",\")), \n        t.endAt && (e += \"|ub:\", e += t.endAt.inclusive ? \"a:\" : \"b:\", e += t.endAt.position.map((e => canonicalId(e))).join(\",\")), \n        t.he = e;\n    }\n    return t.he;\n}\n\nfunction __PRIVATE_targetEquals(e, t) {\n    if (e.limit !== t.limit) return !1;\n    if (e.orderBy.length !== t.orderBy.length) return !1;\n    for (let n = 0; n < e.orderBy.length; n++) if (!__PRIVATE_orderByEquals(e.orderBy[n], t.orderBy[n])) return !1;\n    if (e.filters.length !== t.filters.length) return !1;\n    for (let n = 0; n < e.filters.length; n++) if (!__PRIVATE_filterEquals(e.filters[n], t.filters[n])) return !1;\n    return e.collectionGroup === t.collectionGroup && (!!e.path.isEqual(t.path) && (!!__PRIVATE_boundEquals(e.startAt, t.startAt) && __PRIVATE_boundEquals(e.endAt, t.endAt)));\n}\n\nfunction __PRIVATE_targetIsDocumentTarget(e) {\n    return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length;\n}\n\n/** Returns the field filters that target the given field path. */ function __PRIVATE_targetGetFieldFiltersForPath(e, t) {\n    return e.filters.filter((e => e instanceof FieldFilter && e.field.isEqual(t)));\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction __PRIVATE_targetGetAscendingBound(e, t, n) {\n    let r = re, i = !0;\n    // Process all filters to find a value for the current field segment\n    for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {\n        let e = re, t = !0;\n        switch (n.op) {\n          case \"<\" /* Operator.LESS_THAN */ :\n          case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n            e = __PRIVATE_valuesGetLowerBound(n.value);\n            break;\n\n          case \"==\" /* Operator.EQUAL */ :\n          case \"in\" /* Operator.IN */ :\n          case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n            e = n.value;\n            break;\n\n          case \">\" /* Operator.GREATER_THAN */ :\n            e = n.value, t = !1;\n            break;\n\n          case \"!=\" /* Operator.NOT_EQUAL */ :\n          case \"not-in\" /* Operator.NOT_IN */ :\n            e = re;\n // Remaining filters cannot be used as lower bounds.\n                }\n        __PRIVATE_lowerBoundCompare({\n            value: r,\n            inclusive: i\n        }, {\n            value: e,\n            inclusive: t\n        }) < 0 && (r = e, i = t);\n    }\n    // If there is an additional bound, compare the values against the existing\n    // range to see if we can narrow the scope.\n        if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {\n        if (e.orderBy[s].field.isEqual(t)) {\n            const e = n.position[s];\n            __PRIVATE_lowerBoundCompare({\n                value: r,\n                inclusive: i\n            }, {\n                value: e,\n                inclusive: n.inclusive\n            }) < 0 && (r = e, i = n.inclusive);\n            break;\n        }\n    }\n    return {\n        value: r,\n        inclusive: i\n    };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */ function __PRIVATE_targetGetDescendingBound(e, t, n) {\n    let r = ne, i = !0;\n    // Process all filters to find a value for the current field segment\n    for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {\n        let e = ne, t = !0;\n        switch (n.op) {\n          case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n          case \">\" /* Operator.GREATER_THAN */ :\n            e = __PRIVATE_valuesGetUpperBound(n.value), t = !1;\n            break;\n\n          case \"==\" /* Operator.EQUAL */ :\n          case \"in\" /* Operator.IN */ :\n          case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n            e = n.value;\n            break;\n\n          case \"<\" /* Operator.LESS_THAN */ :\n            e = n.value, t = !1;\n            break;\n\n          case \"!=\" /* Operator.NOT_EQUAL */ :\n          case \"not-in\" /* Operator.NOT_IN */ :\n            e = ne;\n // Remaining filters cannot be used as upper bounds.\n                }\n        __PRIVATE_upperBoundCompare({\n            value: r,\n            inclusive: i\n        }, {\n            value: e,\n            inclusive: t\n        }) > 0 && (r = e, i = t);\n    }\n    // If there is an additional bound, compare the values against the existing\n    // range to see if we can narrow the scope.\n        if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {\n        if (e.orderBy[s].field.isEqual(t)) {\n            const e = n.position[s];\n            __PRIVATE_upperBoundCompare({\n                value: r,\n                inclusive: i\n            }, {\n                value: e,\n                inclusive: n.inclusive\n            }) > 0 && (r = e, i = n.inclusive);\n            break;\n        }\n    }\n    return {\n        value: r,\n        inclusive: i\n    };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nclass __PRIVATE_QueryImpl {\n    /**\n     * Initializes a Query with a path and optional additional query constraints.\n     * Path must currently be empty if this is a collection group query.\n     */\n    constructor(e, t = null, n = [], r = [], i = null, s = \"F\" /* LimitType.First */ , o = null, _ = null) {\n        this.path = e, this.collectionGroup = t, this.explicitOrderBy = n, this.filters = r, \n        this.limit = i, this.limitType = s, this.startAt = o, this.endAt = _, this.Pe = null, \n        // The corresponding `Target` of this `Query` instance.\n        this.Ie = null, this.startAt, this.endAt;\n    }\n}\n\n/** Creates a new Query instance with the options provided. */ function __PRIVATE_newQuery(e, t, n, r, i, s, o, _) {\n    return new __PRIVATE_QueryImpl(e, t, n, r, i, s, o, _);\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */ function __PRIVATE_newQueryForPath(e) {\n    return new __PRIVATE_QueryImpl(e);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nfunction __PRIVATE_queryMatchesAllDocuments(e) {\n    return 0 === e.filters.length && null === e.limit && null == e.startAt && null == e.endAt && (0 === e.explicitOrderBy.length || 1 === e.explicitOrderBy.length && e.explicitOrderBy[0].field.isKeyField());\n}\n\nfunction __PRIVATE_getFirstOrderByField(e) {\n    return e.explicitOrderBy.length > 0 ? e.explicitOrderBy[0].field : null;\n}\n\nfunction __PRIVATE_getInequalityFilterField(e) {\n    for (const t of e.filters) {\n        const e = t.getFirstInequalityField();\n        if (null !== e) return e;\n    }\n    return null;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nfunction __PRIVATE_isCollectionGroupQuery(e) {\n    return null !== e.collectionGroup;\n}\n\n/**\n * Returns the implicit order by constraint that is used to execute the Query,\n * which can be different from the order by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`).\n */ function __PRIVATE_queryOrderBy(e) {\n    const t = __PRIVATE_debugCast(e);\n    if (null === t.Pe) {\n        t.Pe = [];\n        const e = __PRIVATE_getInequalityFilterField(t), n = __PRIVATE_getFirstOrderByField(t);\n        if (null !== e && null === n) \n        // In order to implicitly add key ordering, we must also add the\n        // inequality filter field for it to be a valid query.\n        // Note that the default inequality field and key ordering is ascending.\n        e.isKeyField() || t.Pe.push(new OrderBy(e)), t.Pe.push(new OrderBy(FieldPath$1.keyField(), \"asc\" /* Direction.ASCENDING */)); else {\n            let e = !1;\n            for (const n of t.explicitOrderBy) t.Pe.push(n), n.field.isKeyField() && (e = !0);\n            if (!e) {\n                // The order of the implicit key ordering always matches the last\n                // explicit order by\n                const e = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[t.explicitOrderBy.length - 1].dir : \"asc\" /* Direction.ASCENDING */;\n                t.Pe.push(new OrderBy(FieldPath$1.keyField(), e));\n            }\n        }\n    }\n    return t.Pe;\n}\n\n/**\n * Converts this `Query` instance to it's corresponding `Target` representation.\n */ function __PRIVATE_queryToTarget(e) {\n    const t = __PRIVATE_debugCast(e);\n    if (!t.Ie) if (\"F\" /* LimitType.First */ === t.limitType) t.Ie = __PRIVATE_newTarget(t.path, t.collectionGroup, __PRIVATE_queryOrderBy(t), t.filters, t.limit, t.startAt, t.endAt); else {\n        // Flip the orderBy directions since we want the last results\n        const e = [];\n        for (const n of __PRIVATE_queryOrderBy(t)) {\n            const t = \"desc\" /* Direction.DESCENDING */ === n.dir ? \"asc\" /* Direction.ASCENDING */ : \"desc\" /* Direction.DESCENDING */;\n            e.push(new OrderBy(n.field, t));\n        }\n        // We need to swap the cursors to match the now-flipped query ordering.\n                const n = t.endAt ? new Bound(t.endAt.position, t.endAt.inclusive) : null, r = t.startAt ? new Bound(t.startAt.position, t.startAt.inclusive) : null;\n        // Now return as a LimitType.First query.\n        t.Ie = __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, n, r);\n    }\n    return t.Ie;\n}\n\nfunction __PRIVATE_queryWithAddedFilter(e, t) {\n    t.getFirstInequalityField(), __PRIVATE_getInequalityFilterField(e);\n    const n = e.filters.concat([ t ]);\n    return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), n, e.limit, e.limitType, e.startAt, e.endAt);\n}\n\nfunction __PRIVATE_queryWithLimit(e, t, n) {\n    return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), t, n, e.startAt, e.endAt);\n}\n\nfunction __PRIVATE_queryEquals(e, t) {\n    return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e), __PRIVATE_queryToTarget(t)) && e.limitType === t.limitType;\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nfunction __PRIVATE_canonifyQuery(e) {\n    return `${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`;\n}\n\nfunction __PRIVATE_stringifyQuery(e) {\n    return `Query(target=${function __PRIVATE_stringifyTarget(e) {\n        let t = e.path.canonicalString();\n        return null !== e.collectionGroup && (t += \" collectionGroup=\" + e.collectionGroup), \n        e.filters.length > 0 && (t += `, filters: [${e.filters.map((e => __PRIVATE_stringifyFilter(e))).join(\", \")}]`), \n        __PRIVATE_isNullOrUndefined(e.limit) || (t += \", limit: \" + e.limit), e.orderBy.length > 0 && (t += `, orderBy: [${e.orderBy.map((e => function __PRIVATE_stringifyOrderBy(e) {\n            return `${e.field.canonicalString()} (${e.dir})`;\n        }(e))).join(\", \")}]`), e.startAt && (t += \", startAt: \", t += e.startAt.inclusive ? \"b:\" : \"a:\", \n        t += e.startAt.position.map((e => canonicalId(e))).join(\",\")), e.endAt && (t += \", endAt: \", \n        t += e.endAt.inclusive ? \"a:\" : \"b:\", t += e.endAt.position.map((e => canonicalId(e))).join(\",\")), \n        `Target(${t})`;\n    }(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */ function __PRIVATE_queryMatches(e, t) {\n    return t.isFoundDocument() && function __PRIVATE_queryMatchesPathAndCollectionGroup(e, t) {\n        const n = t.key.path;\n        return null !== e.collectionGroup ? t.key.hasCollectionId(e.collectionGroup) && e.path.isPrefixOf(n) : DocumentKey.isDocumentKey(e.path) ? e.path.isEqual(n) : e.path.isImmediateParentOf(n);\n    }\n    /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */ (e, t) && function __PRIVATE_queryMatchesOrderBy(e, t) {\n        // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).\n        // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n        // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n        // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n        // A document with content of {b:1} matches the filters, but does not match the orderBy because\n        // it's missing the field 'a'.\n        for (const n of __PRIVATE_queryOrderBy(e)) \n        // order by key always matches\n        if (!n.field.isKeyField() && null === t.data.field(n.field)) return !1;\n        return !0;\n    }(e, t) && function __PRIVATE_queryMatchesFilters(e, t) {\n        for (const n of e.filters) if (!n.matches(t)) return !1;\n        return !0;\n    }\n    /** Makes sure a document is within the bounds, if provided. */ (e, t) && function __PRIVATE_queryMatchesBounds(e, t) {\n        if (e.startAt && !\n        /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n        function __PRIVATE_boundSortsBeforeDocument(e, t, n) {\n            const r = __PRIVATE_boundCompareToDocument(e, t, n);\n            return e.inclusive ? r <= 0 : r < 0;\n        }(e.startAt, __PRIVATE_queryOrderBy(e), t)) return !1;\n        if (e.endAt && !function __PRIVATE_boundSortsAfterDocument(e, t, n) {\n            const r = __PRIVATE_boundCompareToDocument(e, t, n);\n            return e.inclusive ? r >= 0 : r > 0;\n        }(e.endAt, __PRIVATE_queryOrderBy(e), t)) return !1;\n        return !0;\n    }\n    /**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */ (e, t);\n}\n\nfunction __PRIVATE_queryCollectionGroup(e) {\n    return e.collectionGroup || (e.path.length % 2 == 1 ? e.path.lastSegment() : e.path.get(e.path.length - 2));\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */ function __PRIVATE_newQueryComparator(e) {\n    return (t, n) => {\n        let r = !1;\n        for (const i of __PRIVATE_queryOrderBy(e)) {\n            const e = __PRIVATE_compareDocs(i, t, n);\n            if (0 !== e) return e;\n            r = r || i.field.isKeyField();\n        }\n        return 0;\n    };\n}\n\nfunction __PRIVATE_compareDocs(e, t, n) {\n    const r = e.field.isKeyField() ? DocumentKey.comparator(t.key, n.key) : function __PRIVATE_compareDocumentsByField(e, t, n) {\n        const r = t.data.field(e), i = n.data.field(e);\n        return null !== r && null !== i ? __PRIVATE_valueCompare(r, i) : fail();\n    }(e.field, t, n);\n    switch (e.dir) {\n      case \"asc\" /* Direction.ASCENDING */ :\n        return r;\n\n      case \"desc\" /* Direction.DESCENDING */ :\n        return -1 * r;\n\n      default:\n        return fail();\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */ class ObjectMap {\n    constructor(e, t) {\n        this.mapKeyFn = e, this.equalsFn = t, \n        /**\n         * The inner map for a key/value pair. Due to the possibility of collisions we\n         * keep a list of entries that we do a linear search through to find an actual\n         * match. Note that collisions should be rare, so we still expect near\n         * constant time lookups in practice.\n         */\n        this.inner = {}, \n        /** The number of entries stored in the map */\n        this.innerSize = 0;\n    }\n    /** Get a value for this key, or undefined if it does not exist. */    get(e) {\n        const t = this.mapKeyFn(e), n = this.inner[t];\n        if (void 0 !== n) for (const [t, r] of n) if (this.equalsFn(t, e)) return r;\n    }\n    has(e) {\n        return void 0 !== this.get(e);\n    }\n    /** Put this key and value in the map. */    set(e, t) {\n        const n = this.mapKeyFn(e), r = this.inner[n];\n        if (void 0 === r) return this.inner[n] = [ [ e, t ] ], void this.innerSize++;\n        for (let n = 0; n < r.length; n++) if (this.equalsFn(r[n][0], e)) \n        // This is updating an existing entry and does not increase `innerSize`.\n        return void (r[n] = [ e, t ]);\n        r.push([ e, t ]), this.innerSize++;\n    }\n    /**\n     * Remove this key from the map. Returns a boolean if anything was deleted.\n     */    delete(e) {\n        const t = this.mapKeyFn(e), n = this.inner[t];\n        if (void 0 === n) return !1;\n        for (let r = 0; r < n.length; r++) if (this.equalsFn(n[r][0], e)) return 1 === n.length ? delete this.inner[t] : n.splice(r, 1), \n        this.innerSize--, !0;\n        return !1;\n    }\n    forEach(e) {\n        forEach(this.inner, ((t, n) => {\n            for (const [t, r] of n) e(t, r);\n        }));\n    }\n    isEmpty() {\n        return isEmpty(this.inner);\n    }\n    size() {\n        return this.innerSize;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const ie = new SortedMap(DocumentKey.comparator);\n\nfunction __PRIVATE_mutableDocumentMap() {\n    return ie;\n}\n\nconst se = new SortedMap(DocumentKey.comparator);\n\nfunction documentMap(...e) {\n    let t = se;\n    for (const n of e) t = t.insert(n.key, n);\n    return t;\n}\n\nfunction __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) {\n    let t = se;\n    return e.forEach(((e, n) => t = t.insert(e, n.overlayedDocument))), t;\n}\n\nfunction __PRIVATE_newOverlayMap() {\n    return __PRIVATE_newDocumentKeyMap();\n}\n\nfunction __PRIVATE_newMutationMap() {\n    return __PRIVATE_newDocumentKeyMap();\n}\n\nfunction __PRIVATE_newDocumentKeyMap() {\n    return new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t)));\n}\n\nconst oe = new SortedMap(DocumentKey.comparator);\n\nconst _e = new SortedSet(DocumentKey.comparator);\n\nfunction __PRIVATE_documentKeySet(...e) {\n    let t = _e;\n    for (const n of e) t = t.add(n);\n    return t;\n}\n\nconst ae = new SortedSet(__PRIVATE_primitiveComparator);\n\nfunction __PRIVATE_targetIdSet() {\n    return ae;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */ function __PRIVATE_toDouble(e, t) {\n    if (e.useProto3Json) {\n        if (isNaN(t)) return {\n            doubleValue: \"NaN\"\n        };\n        if (t === 1 / 0) return {\n            doubleValue: \"Infinity\"\n        };\n        if (t === -1 / 0) return {\n            doubleValue: \"-Infinity\"\n        };\n    }\n    return {\n        doubleValue: __PRIVATE_isNegativeZero(t) ? \"-0\" : t\n    };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */ function __PRIVATE_toInteger(e) {\n    return {\n        integerValue: \"\" + e\n    };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */ function toNumber(e, t) {\n    return isSafeInteger(t) ? __PRIVATE_toInteger(t) : __PRIVATE_toDouble(e, t);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Used to represent a field transform on a mutation. */ class TransformOperation {\n    constructor() {\n        // Make sure that the structural type of `TransformOperation` is unique.\n        // See https://github.com/microsoft/TypeScript/issues/5451\n        this._ = void 0;\n    }\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */ function __PRIVATE_applyTransformOperationToLocalView(e, t, n) {\n    return e instanceof __PRIVATE_ServerTimestampTransform ? function serverTimestamp$1(e, t) {\n        const n = {\n            fields: {\n                __type__: {\n                    stringValue: \"server_timestamp\"\n                },\n                __local_write_time__: {\n                    timestampValue: {\n                        seconds: e.seconds,\n                        nanos: e.nanoseconds\n                    }\n                }\n            }\n        };\n        // We should avoid storing deeply nested server timestamp map values\n        // because we never use the intermediate \"previous values\".\n        // For example:\n        // previous: 42L, add: t1, result: t1 -> 42L\n        // previous: t1,  add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n        // previous: t2,  add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n        // `getPreviousValue` recursively traverses server timestamps to find the\n        // least recent Value.\n                return t && __PRIVATE_isServerTimestamp(t) && (t = __PRIVATE_getPreviousValue(t)), \n        t && (n.fields.__previous_value__ = t), {\n            mapValue: n\n        };\n    }(n, t) : e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e, t) {\n        // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n        // precision and resolves overflows by reducing precision, we do not\n        // manually cap overflows at 2^63.\n        const n = __PRIVATE_computeTransformOperationBaseValue(e, t), r = asNumber(n) + asNumber(e.Te);\n        return isInteger(n) && isInteger(e.Te) ? __PRIVATE_toInteger(r) : __PRIVATE_toDouble(e.serializer, r);\n    }(e, t);\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */ function __PRIVATE_applyTransformOperationToRemoteDocument(e, t, n) {\n    // The server just sends null as the transform result for array operations,\n    // so we have to calculate a result the same as we do for local\n    // applications.\n    return e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : n;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */ function __PRIVATE_computeTransformOperationBaseValue(e, t) {\n    return e instanceof __PRIVATE_NumericIncrementTransformOperation ? \n    /** Returns true if `value` is either an IntegerValue or a DoubleValue. */\n    function __PRIVATE_isNumber(e) {\n        return isInteger(e) || function __PRIVATE_isDouble(e) {\n            return !!e && \"doubleValue\" in e;\n        }(e);\n    }(t) ? t : {\n        integerValue: 0\n    } : null;\n}\n\n/** Transforms a value into a server-generated timestamp. */\nclass __PRIVATE_ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation {\n    constructor(e) {\n        super(), this.elements = e;\n    }\n}\n\nfunction __PRIVATE_applyArrayUnionTransformOperation(e, t) {\n    const n = __PRIVATE_coercedFieldValuesArray(t);\n    for (const t of e.elements) n.some((e => __PRIVATE_valueEquals(e, t))) || n.push(t);\n    return {\n        arrayValue: {\n            values: n\n        }\n    };\n}\n\n/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation {\n    constructor(e) {\n        super(), this.elements = e;\n    }\n}\n\nfunction __PRIVATE_applyArrayRemoveTransformOperation(e, t) {\n    let n = __PRIVATE_coercedFieldValuesArray(t);\n    for (const t of e.elements) n = n.filter((e => !__PRIVATE_valueEquals(e, t)));\n    return {\n        arrayValue: {\n            values: n\n        }\n    };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation {\n    constructor(e, t) {\n        super(), this.serializer = e, this.Te = t;\n    }\n}\n\nfunction asNumber(e) {\n    return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);\n}\n\nfunction __PRIVATE_coercedFieldValuesArray(e) {\n    return isArray(e) && e.arrayValue.values ? e.arrayValue.values.slice() : [];\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A field path and the TransformOperation to perform upon it. */ class FieldTransform {\n    constructor(e, t) {\n        this.field = e, this.transform = t;\n    }\n}\n\nfunction __PRIVATE_fieldTransformEquals(e, t) {\n    return e.field.isEqual(t.field) && function __PRIVATE_transformOperationEquals(e, t) {\n        return e instanceof __PRIVATE_ArrayUnionTransformOperation && t instanceof __PRIVATE_ArrayUnionTransformOperation || e instanceof __PRIVATE_ArrayRemoveTransformOperation && t instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_arrayEquals(e.elements, t.elements, __PRIVATE_valueEquals) : e instanceof __PRIVATE_NumericIncrementTransformOperation && t instanceof __PRIVATE_NumericIncrementTransformOperation ? __PRIVATE_valueEquals(e.Te, t.Te) : e instanceof __PRIVATE_ServerTimestampTransform && t instanceof __PRIVATE_ServerTimestampTransform;\n    }(e.transform, t.transform);\n}\n\n/** The result of successfully applying a mutation to the backend. */\nclass MutationResult {\n    constructor(\n    /**\n     * The version at which the mutation was committed:\n     *\n     * - For most operations, this is the updateTime in the WriteResult.\n     * - For deletes, the commitTime of the WriteResponse (because deletes are\n     *   not stored and have no updateTime).\n     *\n     * Note that these versions can be different: No-op writes will not change\n     * the updateTime even though the commitTime advances.\n     */\n    e, \n    /**\n     * The resulting fields returned from the backend after a mutation\n     * containing field transforms has been committed. Contains one FieldValue\n     * for each FieldTransform that was in the mutation.\n     *\n     * Will be empty if the mutation did not contain any field transforms.\n     */\n    t) {\n        this.version = e, this.transformResults = t;\n    }\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */ class Precondition {\n    constructor(e, t) {\n        this.updateTime = e, this.exists = t;\n    }\n    /** Creates a new empty Precondition. */    static none() {\n        return new Precondition;\n    }\n    /** Creates a new Precondition with an exists flag. */    static exists(e) {\n        return new Precondition(void 0, e);\n    }\n    /** Creates a new Precondition based on a version a document exists at. */    static updateTime(e) {\n        return new Precondition(e);\n    }\n    /** Returns whether this Precondition is empty. */    get isNone() {\n        return void 0 === this.updateTime && void 0 === this.exists;\n    }\n    isEqual(e) {\n        return this.exists === e.exists && (this.updateTime ? !!e.updateTime && this.updateTime.isEqual(e.updateTime) : !e.updateTime);\n    }\n}\n\n/** Returns true if the preconditions is valid for the given document. */ function __PRIVATE_preconditionIsValidForDocument(e, t) {\n    return void 0 !== e.updateTime ? t.isFoundDocument() && t.version.isEqual(e.updateTime) : void 0 === e.exists || e.exists === t.isFoundDocument();\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION           APPLIED TO            RESULTS IN\n *\n * SetMutation        Document(v3)          Document(v3)\n * SetMutation        NoDocument(v3)        Document(v0)\n * SetMutation        InvalidDocument(v0)   Document(v0)\n * PatchMutation      Document(v3)          Document(v3)\n * PatchMutation      NoDocument(v3)        NoDocument(v3)\n * PatchMutation      InvalidDocument(v0)   UnknownDocument(v3)\n * DeleteMutation     Document(v3)          NoDocument(v0)\n * DeleteMutation     NoDocument(v3)        NoDocument(v0)\n * DeleteMutation     InvalidDocument(v0)   NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */ class Mutation {}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */ function __PRIVATE_calculateOverlayMutation(e, t) {\n    if (!e.hasLocalMutations || t && 0 === t.fields.length) return null;\n    // mask is null when sets or deletes are applied to the current document.\n        if (null === t) return e.isNoDocument() ? new __PRIVATE_DeleteMutation(e.key, Precondition.none()) : new __PRIVATE_SetMutation(e.key, e.data, Precondition.none());\n    {\n        const n = e.data, r = ObjectValue.empty();\n        let i = new SortedSet(FieldPath$1.comparator);\n        for (let e of t.fields) if (!i.has(e)) {\n            let t = n.field(e);\n            // If we are deleting a nested field, we take the immediate parent as\n            // the mask used to construct the resulting mutation.\n            // Justification: Nested fields can create parent fields implicitly. If\n            // only a leaf entry is deleted in later mutations, the parent field\n            // should still remain, but we may have lost this information.\n            // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n            // This leaves the final result (foo, {}). Despite the fact that `doc`\n            // has the correct result, `foo` is not in `mask`, and the resulting\n            // mutation would miss `foo`.\n                        null === t && e.length > 1 && (e = e.popLast(), t = n.field(e)), null === t ? r.delete(e) : r.set(e, t), \n            i = i.add(e);\n        }\n        return new __PRIVATE_PatchMutation(e.key, r, new FieldMask(i.toArray()), Precondition.none());\n    }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n *     invalid document if the client has no knowledge of the pre-mutation state\n *     of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */ function __PRIVATE_mutationApplyToRemoteDocument(e, t, n) {\n    e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToRemoteDocument(e, t, n) {\n        // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n        // remote document the server has accepted the mutation so the precondition\n        // must have held.\n        const r = e.value.clone(), i = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults);\n        r.setAll(i), t.convertToFoundDocument(n.version, r).setHasCommittedMutations();\n    }(e, t, n) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToRemoteDocument(e, t, n) {\n        if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) \n        // Since the mutation was not rejected, we know that the precondition\n        // matched on the backend. We therefore must not have the expected version\n        // of the document in our cache and convert to an UnknownDocument with a\n        // known updateTime.\n        return void t.convertToUnknownDocument(n.version);\n        const r = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults), i = t.data;\n        i.setAll(__PRIVATE_getPatch(e)), i.setAll(r), t.convertToFoundDocument(n.version, i).setHasCommittedMutations();\n    }(e, t, n) : function __PRIVATE_deleteMutationApplyToRemoteDocument(e, t, n) {\n        // Unlike applyToLocalView, if we're applying a mutation to a remote\n        // document the server has accepted the mutation so the precondition must\n        // have held.\n        t.convertToNoDocument(n.version).setHasCommittedMutations();\n    }(0, t, n);\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n *     invalid document if the client has no knowledge of the pre-mutation state\n *     of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n *     batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */ function __PRIVATE_mutationApplyToLocalView(e, t, n, r) {\n    return e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToLocalView(e, t, n, r) {\n        if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) \n        // The mutation failed to apply (e.g. a document ID created with add()\n        // caused a name collision).\n        return n;\n        const i = e.value.clone(), s = __PRIVATE_localTransformResults(e.fieldTransforms, r, t);\n        return i.setAll(s), t.convertToFoundDocument(t.version, i).setHasLocalMutations(), \n        null;\n // SetMutation overwrites all fields.\n        }\n    /**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n *  * When a field is in both the mask and the values, the corresponding field\n *    is updated.\n *  * When a field is in neither the mask nor the values, the corresponding\n *    field is unmodified.\n *  * When a field is in the mask but not in the values, the corresponding field\n *    is deleted.\n *  * When a field is not in the mask but is in the values, the values map is\n *    ignored.\n */ (e, t, n, r) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToLocalView(e, t, n, r) {\n        if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return n;\n        const i = __PRIVATE_localTransformResults(e.fieldTransforms, r, t), s = t.data;\n        if (s.setAll(__PRIVATE_getPatch(e)), s.setAll(i), t.convertToFoundDocument(t.version, s).setHasLocalMutations(), \n        null === n) return null;\n        return n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e => e.field)));\n    }\n    /**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */ (e, t, n, r) : function __PRIVATE_deleteMutationApplyToLocalView(e, t, n) {\n        if (__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return t.convertToNoDocument(t.version).setHasLocalMutations(), \n        null;\n        return n;\n    }\n    /**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */ (e, t, n);\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */ function __PRIVATE_mutationExtractBaseValue(e, t) {\n    let n = null;\n    for (const r of e.fieldTransforms) {\n        const e = t.data.field(r.field), i = __PRIVATE_computeTransformOperationBaseValue(r.transform, e || null);\n        null != i && (null === n && (n = ObjectValue.empty()), n.set(r.field, i));\n    }\n    return n || null;\n}\n\nfunction __PRIVATE_mutationEquals(e, t) {\n    return e.type === t.type && (!!e.key.isEqual(t.key) && (!!e.precondition.isEqual(t.precondition) && (!!function __PRIVATE_fieldTransformsAreEqual(e, t) {\n        return void 0 === e && void 0 === t || !(!e || !t) && __PRIVATE_arrayEquals(e, t, ((e, t) => __PRIVATE_fieldTransformEquals(e, t)));\n    }(e.fieldTransforms, t.fieldTransforms) && (0 /* MutationType.Set */ === e.type ? e.value.isEqual(t.value) : 1 /* MutationType.Patch */ !== e.type || e.data.isEqual(t.data) && e.fieldMask.isEqual(t.fieldMask)))));\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */ class __PRIVATE_SetMutation extends Mutation {\n    constructor(e, t, n, r = []) {\n        super(), this.key = e, this.value = t, this.precondition = n, this.fieldTransforms = r, \n        this.type = 0 /* MutationType.Set */;\n    }\n    getFieldMask() {\n        return null;\n    }\n}\n\nclass __PRIVATE_PatchMutation extends Mutation {\n    constructor(e, t, n, r, i = []) {\n        super(), this.key = e, this.data = t, this.fieldMask = n, this.precondition = r, \n        this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;\n    }\n    getFieldMask() {\n        return this.fieldMask;\n    }\n}\n\nfunction __PRIVATE_getPatch(e) {\n    const t = new Map;\n    return e.fieldMask.fields.forEach((n => {\n        if (!n.isEmpty()) {\n            const r = e.data.field(n);\n            t.set(n, r);\n        }\n    })), t;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */ function __PRIVATE_serverTransformResults(e, t, n) {\n    const r = new Map;\n    __PRIVATE_hardAssert(e.length === n.length);\n    for (let i = 0; i < n.length; i++) {\n        const s = e[i], o = s.transform, _ = t.data.field(s.field);\n        r.set(s.field, __PRIVATE_applyTransformOperationToRemoteDocument(o, _, n[i]));\n    }\n    return r;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n *     generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */ function __PRIVATE_localTransformResults(e, t, n) {\n    const r = new Map;\n    for (const i of e) {\n        const e = i.transform, s = n.data.field(i.field);\n        r.set(i.field, __PRIVATE_applyTransformOperationToLocalView(e, s, t));\n    }\n    return r;\n}\n\n/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation {\n    constructor(e, t) {\n        super(), this.key = e, this.precondition = t, this.type = 2 /* MutationType.Delete */ , \n        this.fieldTransforms = [];\n    }\n    getFieldMask() {\n        return null;\n    }\n}\n\nclass __PRIVATE_VerifyMutation extends Mutation {\n    constructor(e, t) {\n        super(), this.key = e, this.precondition = t, this.type = 3 /* MutationType.Verify */ , \n        this.fieldTransforms = [];\n    }\n    getFieldMask() {\n        return null;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */ class MutationBatch {\n    /**\n     * @param batchId - The unique ID of this mutation batch.\n     * @param localWriteTime - The original write time of this mutation.\n     * @param baseMutations - Mutations that are used to populate the base\n     * values when this mutation is applied locally. This can be used to locally\n     * overwrite values that are persisted in the remote document cache. Base\n     * mutations are never sent to the backend.\n     * @param mutations - The user-provided mutations in this mutation batch.\n     * User-provided mutations are applied both locally and remotely on the\n     * backend.\n     */\n    constructor(e, t, n, r) {\n        this.batchId = e, this.localWriteTime = t, this.baseMutations = n, this.mutations = r;\n    }\n    /**\n     * Applies all the mutations in this MutationBatch to the specified document\n     * to compute the state of the remote document\n     *\n     * @param document - The document to apply mutations to.\n     * @param batchResult - The result of applying the MutationBatch to the\n     * backend.\n     */    applyToRemoteDocument(e, t) {\n        const n = t.mutationResults;\n        for (let t = 0; t < this.mutations.length; t++) {\n            const r = this.mutations[t];\n            if (r.key.isEqual(e.key)) {\n                __PRIVATE_mutationApplyToRemoteDocument(r, e, n[t]);\n            }\n        }\n    }\n    /**\n     * Computes the local view of a document given all the mutations in this\n     * batch.\n     *\n     * @param document - The document to apply mutations to.\n     * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n     * @returns A `FieldMask` representing all the fields that are mutated.\n     */    applyToLocalView(e, t) {\n        // First, apply the base state. This allows us to apply non-idempotent\n        // transform against a consistent set of values.\n        for (const n of this.baseMutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));\n        // Second, apply all user-provided mutations.\n                for (const n of this.mutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));\n        return t;\n    }\n    /**\n     * Computes the local view for all provided documents given the mutations in\n     * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n     * replace all the mutation applications.\n     */    applyToLocalDocumentSet(e, t) {\n        // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n        // directly (as done in `applyToLocalView()`), we can reduce the complexity\n        // to O(n).\n        const n = __PRIVATE_newMutationMap();\n        return this.mutations.forEach((r => {\n            const i = e.get(r.key), s = i.overlayedDocument;\n            // TODO(mutabledocuments): This method should take a MutableDocumentMap\n            // and we should remove this cast.\n                        let o = this.applyToLocalView(s, i.mutatedFields);\n            // Set mutatedFields to null if the document is only from local mutations.\n            // This creates a Set or Delete mutation, instead of trying to create a\n            // patch mutation as the overlay.\n                        o = t.has(r.key) ? null : o;\n            const _ = __PRIVATE_calculateOverlayMutation(s, o);\n            null !== _ && n.set(r.key, _), s.isValidDocument() || s.convertToNoDocument(SnapshotVersion.min());\n        })), n;\n    }\n    keys() {\n        return this.mutations.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet());\n    }\n    isEqual(e) {\n        return this.batchId === e.batchId && __PRIVATE_arrayEquals(this.mutations, e.mutations, ((e, t) => __PRIVATE_mutationEquals(e, t))) && __PRIVATE_arrayEquals(this.baseMutations, e.baseMutations, ((e, t) => __PRIVATE_mutationEquals(e, t)));\n    }\n}\n\n/** The result of applying a mutation batch to the backend. */ class MutationBatchResult {\n    constructor(e, t, n, \n    /**\n     * A pre-computed mapping from each mutated document to the resulting\n     * version.\n     */\n    r) {\n        this.batch = e, this.commitVersion = t, this.mutationResults = n, this.docVersions = r;\n    }\n    /**\n     * Creates a new MutationBatchResult for the given batch and results. There\n     * must be one result for each mutation in the batch. This static factory\n     * caches a document=&gt;version mapping (docVersions).\n     */    static from(e, t, n) {\n        __PRIVATE_hardAssert(e.mutations.length === n.length);\n        let r = function __PRIVATE_documentVersionMap() {\n            return oe;\n        }();\n        const i = e.mutations;\n        for (let e = 0; e < i.length; e++) r = r.insert(i[e].key, n[e].version);\n        return new MutationBatchResult(e, t, n, r);\n    }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */ class Overlay {\n    constructor(e, t) {\n        this.largestBatchId = e, this.mutation = t;\n    }\n    getKey() {\n        return this.mutation.key;\n    }\n    isEqual(e) {\n        return null !== e && this.mutation === e.mutation;\n    }\n    toString() {\n        return `Overlay{\\n      largestBatchId: ${this.largestBatchId},\\n      mutation: ${this.mutation.toString()}\\n    }`;\n    }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Concrete implementation of the Aggregate type.\n */ class __PRIVATE_AggregateImpl {\n    constructor(e, t, n) {\n        this.alias = e, this.Ee = t, this.fieldPath = n;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class ExistenceFilter {\n    constructor(e, t) {\n        this.count = e, this.unchangedNames = t;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */ var ue, ce;\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nfunction __PRIVATE_isPermanentError(e) {\n    switch (e) {\n      default:\n        return fail();\n\n      case v.CANCELLED:\n      case v.UNKNOWN:\n      case v.DEADLINE_EXCEEDED:\n      case v.RESOURCE_EXHAUSTED:\n      case v.INTERNAL:\n      case v.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n        // to retry with new credentials which will happen automatically.\n              case v.UNAUTHENTICATED:\n        return !1;\n\n      case v.INVALID_ARGUMENT:\n      case v.NOT_FOUND:\n      case v.ALREADY_EXISTS:\n      case v.PERMISSION_DENIED:\n      case v.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n        // the context and should handled individually by the calling code.\n        // See https://cloud.google.com/apis/design/errors.\n              case v.ABORTED:\n      case v.OUT_OF_RANGE:\n      case v.UNIMPLEMENTED:\n      case v.DATA_LOSS:\n        return !0;\n    }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n *     is no match.\n */\nfunction __PRIVATE_mapCodeFromRpcCode(e) {\n    if (void 0 === e) \n    // This shouldn't normally happen, but in certain error cases (like trying\n    // to send invalid proto messages) we may get an error with no GRPC code.\n    return __PRIVATE_logError(\"GRPC error has no .code\"), v.UNKNOWN;\n    switch (e) {\n      case ue.OK:\n        return v.OK;\n\n      case ue.CANCELLED:\n        return v.CANCELLED;\n\n      case ue.UNKNOWN:\n        return v.UNKNOWN;\n\n      case ue.DEADLINE_EXCEEDED:\n        return v.DEADLINE_EXCEEDED;\n\n      case ue.RESOURCE_EXHAUSTED:\n        return v.RESOURCE_EXHAUSTED;\n\n      case ue.INTERNAL:\n        return v.INTERNAL;\n\n      case ue.UNAVAILABLE:\n        return v.UNAVAILABLE;\n\n      case ue.UNAUTHENTICATED:\n        return v.UNAUTHENTICATED;\n\n      case ue.INVALID_ARGUMENT:\n        return v.INVALID_ARGUMENT;\n\n      case ue.NOT_FOUND:\n        return v.NOT_FOUND;\n\n      case ue.ALREADY_EXISTS:\n        return v.ALREADY_EXISTS;\n\n      case ue.PERMISSION_DENIED:\n        return v.PERMISSION_DENIED;\n\n      case ue.FAILED_PRECONDITION:\n        return v.FAILED_PRECONDITION;\n\n      case ue.ABORTED:\n        return v.ABORTED;\n\n      case ue.OUT_OF_RANGE:\n        return v.OUT_OF_RANGE;\n\n      case ue.UNIMPLEMENTED:\n        return v.UNIMPLEMENTED;\n\n      case ue.DATA_LOSS:\n        return v.DATA_LOSS;\n\n      default:\n        return fail();\n    }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n *     Code.UNKNOWN.\n */ (ce = ue || (ue = {}))[ce.OK = 0] = \"OK\", ce[ce.CANCELLED = 1] = \"CANCELLED\", \nce[ce.UNKNOWN = 2] = \"UNKNOWN\", ce[ce.INVALID_ARGUMENT = 3] = \"INVALID_ARGUMENT\", \nce[ce.DEADLINE_EXCEEDED = 4] = \"DEADLINE_EXCEEDED\", ce[ce.NOT_FOUND = 5] = \"NOT_FOUND\", \nce[ce.ALREADY_EXISTS = 6] = \"ALREADY_EXISTS\", ce[ce.PERMISSION_DENIED = 7] = \"PERMISSION_DENIED\", \nce[ce.UNAUTHENTICATED = 16] = \"UNAUTHENTICATED\", ce[ce.RESOURCE_EXHAUSTED = 8] = \"RESOURCE_EXHAUSTED\", \nce[ce.FAILED_PRECONDITION = 9] = \"FAILED_PRECONDITION\", ce[ce.ABORTED = 10] = \"ABORTED\", \nce[ce.OUT_OF_RANGE = 11] = \"OUT_OF_RANGE\", ce[ce.UNIMPLEMENTED = 12] = \"UNIMPLEMENTED\", \nce[ce.INTERNAL = 13] = \"INTERNAL\", ce[ce.UNAVAILABLE = 14] = \"UNAVAILABLE\", ce[ce.DATA_LOSS = 15] = \"DATA_LOSS\";\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Manages \"testing hooks\", hooks into the internals of the SDK to verify\n * internal state and events during integration tests. Do not use this class\n * except for testing purposes.\n *\n * There are two ways to retrieve the global singleton instance of this class:\n * 1. The `instance` property, which returns null if the global singleton\n *      instance has not been created. Use this property if the caller should\n *      \"do nothing\" if there are no testing hooks registered, such as when\n *      delivering an event to notify registered callbacks.\n * 2. The `getOrCreateInstance()` method, which creates the global singleton\n *      instance if it has not been created. Use this method if the instance is\n *      needed to, for example, register a callback.\n *\n * @internal\n */\nclass __PRIVATE_TestingHooks {\n    constructor() {\n        this.onExistenceFilterMismatchCallbacks = new Map;\n    }\n    /**\n     * Returns the singleton instance of this class, or null if it has not been\n     * initialized.\n     */    static get instance() {\n        return le;\n    }\n    /**\n     * Returns the singleton instance of this class, creating it if is has never\n     * been created before.\n     */    static getOrCreateInstance() {\n        return null === le && (le = new __PRIVATE_TestingHooks), le;\n    }\n    /**\n     * Registers a callback to be notified when an existence filter mismatch\n     * occurs in the Watch listen stream.\n     *\n     * The relative order in which callbacks are notified is unspecified; do not\n     * rely on any particular ordering. If a given callback is registered multiple\n     * times then it will be notified multiple times, once per registration.\n     *\n     * @param callback the callback to invoke upon existence filter mismatch.\n     *\n     * @return a function that, when called, unregisters the given callback; only\n     * the first invocation of the returned function does anything; all subsequent\n     * invocations do nothing.\n     */    onExistenceFilterMismatch(e) {\n        const t = Symbol();\n        return this.onExistenceFilterMismatchCallbacks.set(t, e), () => this.onExistenceFilterMismatchCallbacks.delete(t);\n    }\n    /**\n     * Invokes all currently-registered `onExistenceFilterMismatch` callbacks.\n     * @param info Information about the existence filter mismatch.\n     */    notifyOnExistenceFilterMismatch(e) {\n        this.onExistenceFilterMismatchCallbacks.forEach((t => t(e)));\n    }\n}\n\n/** The global singleton instance of `TestingHooks`. */ let le = null;\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */ function __PRIVATE_newTextEncoder() {\n    return new TextEncoder;\n}\n\n/**\n * An instance of the Platform's 'TextDecoder' implementation.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst he = new Integer([ 4294967295, 4294967295 ], 0);\n\n// Hash a string using md5 hashing algorithm.\nfunction __PRIVATE_getMd5HashValue(e) {\n    const t = __PRIVATE_newTextEncoder().encode(e), n = new Md5;\n    return n.update(t), new Uint8Array(n.digest());\n}\n\n// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using\n// 2’s complement using little endian.\nfunction __PRIVATE_get64BitUints(e) {\n    const t = new DataView(e.buffer), n = t.getUint32(0, /* littleEndian= */ !0), r = t.getUint32(4, /* littleEndian= */ !0), i = t.getUint32(8, /* littleEndian= */ !0), s = t.getUint32(12, /* littleEndian= */ !0);\n    return [ new Integer([ n, r ], 0), new Integer([ i, s ], 0) ];\n}\n\nclass BloomFilter {\n    constructor(e, t, n) {\n        if (this.bitmap = e, this.padding = t, this.hashCount = n, t < 0 || t >= 8) throw new __PRIVATE_BloomFilterError(`Invalid padding: ${t}`);\n        if (n < 0) throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);\n        if (e.length > 0 && 0 === this.hashCount) \n        // Only empty bloom filter can have 0 hash count.\n        throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);\n        if (0 === e.length && 0 !== t) \n        // Empty bloom filter should have 0 padding.\n        throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${t}`);\n        this.de = 8 * e.length - t, \n        // Set the bit count in Integer to avoid repetition in mightContain().\n        this.Ae = Integer.fromNumber(this.de);\n    }\n    // Calculate the ith hash value based on the hashed 64bit integers,\n    // and calculate its corresponding bit index in the bitmap to be checked.\n    Re(e, t, n) {\n        // Calculate hashed value h(i) = h1 + (i * h2).\n        let r = e.add(t.multiply(Integer.fromNumber(n)));\n        // Wrap if hash value overflow 64bit.\n                return 1 === r.compare(he) && (r = new Integer([ r.getBits(0), r.getBits(1) ], 0)), \n        r.modulo(this.Ae).toNumber();\n    }\n    // Return whether the bit on the given index in the bitmap is set to 1.\n    Ve(e) {\n        return 0 != (this.bitmap[Math.floor(e / 8)] & 1 << e % 8);\n    }\n    mightContain(e) {\n        // Empty bitmap should always return false on membership check.\n        if (0 === this.de) return !1;\n        const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);\n        for (let e = 0; e < this.hashCount; e++) {\n            const t = this.Re(n, r, e);\n            if (!this.Ve(t)) return !1;\n        }\n        return !0;\n    }\n    /** Create bloom filter for testing purposes only. */    static create(e, t, n) {\n        const r = e % 8 == 0 ? 0 : 8 - e % 8, i = new Uint8Array(Math.ceil(e / 8)), s = new BloomFilter(i, r, t);\n        return n.forEach((e => s.insert(e))), s;\n    }\n    insert(e) {\n        if (0 === this.de) return;\n        const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);\n        for (let e = 0; e < this.hashCount; e++) {\n            const t = this.Re(n, r, e);\n            this.me(t);\n        }\n    }\n    me(e) {\n        const t = Math.floor(e / 8), n = e % 8;\n        this.bitmap[t] |= 1 << n;\n    }\n}\n\nclass __PRIVATE_BloomFilterError extends Error {\n    constructor() {\n        super(...arguments), this.name = \"BloomFilterError\";\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */ class RemoteEvent {\n    constructor(\n    /**\n     * The snapshot version this event brings us up to, or MIN if not set.\n     */\n    e, \n    /**\n     * A map from target to changes to the target. See TargetChange.\n     */\n    t, \n    /**\n     * A map of targets that is known to be inconsistent, and the purpose for\n     * re-listening. Listens for these targets should be re-established without\n     * resume tokens.\n     */\n    n, \n    /**\n     * A set of which documents have changed or been deleted, along with the\n     * doc's new values (if not deleted).\n     */\n    r, \n    /**\n     * A set of which document updates are due only to limbo resolution targets.\n     */\n    i) {\n        this.snapshotVersion = e, this.targetChanges = t, this.targetMismatches = n, this.documentUpdates = r, \n        this.resolvedLimboDocuments = i;\n    }\n    /**\n     * HACK: Views require RemoteEvents in order to determine whether the view is\n     * CURRENT, but secondary tabs don't receive remote events. So this method is\n     * used to create a synthesized RemoteEvent that can be used to apply a\n     * CURRENT status change to a View, for queries executed in a different tab.\n     */\n    // PORTING NOTE: Multi-tab only\n    static createSynthesizedRemoteEventForCurrentChange(e, t, n) {\n        const r = new Map;\n        return r.set(e, TargetChange.createSynthesizedTargetChangeForCurrentChange(e, t, n)), \n        new RemoteEvent(SnapshotVersion.min(), r, new SortedMap(__PRIVATE_primitiveComparator), __PRIVATE_mutableDocumentMap(), __PRIVATE_documentKeySet());\n    }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */ class TargetChange {\n    constructor(\n    /**\n     * An opaque, server-assigned token that allows watching a query to be resumed\n     * after disconnecting without retransmitting all the data that matches the\n     * query. The resume token essentially identifies a point in time from which\n     * the server should resume sending results.\n     */\n    e, \n    /**\n     * The \"current\" (synced) status of this target. Note that \"current\"\n     * has special meaning in the RPC protocol that implies that a target is\n     * both up-to-date and consistent with the rest of the watch stream.\n     */\n    t, \n    /**\n     * The set of documents that were newly assigned to this target as part of\n     * this remote event.\n     */\n    n, \n    /**\n     * The set of documents that were already assigned to this target but received\n     * an update during this remote event.\n     */\n    r, \n    /**\n     * The set of documents that were removed from this target as part of this\n     * remote event.\n     */\n    i) {\n        this.resumeToken = e, this.current = t, this.addedDocuments = n, this.modifiedDocuments = r, \n        this.removedDocuments = i;\n    }\n    /**\n     * This method is used to create a synthesized TargetChanges that can be used to\n     * apply a CURRENT status change to a View (for queries executed in a different\n     * tab) or for new queries (to raise snapshots with correct CURRENT status).\n     */    static createSynthesizedTargetChangeForCurrentChange(e, t, n) {\n        return new TargetChange(n, t, __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet());\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */ class __PRIVATE_DocumentWatchChange {\n    constructor(\n    /** The new document applies to all of these targets. */\n    e, \n    /** The new document is removed from all of these targets. */\n    t, \n    /** The key of the document for this change. */\n    n, \n    /**\n     * The new document or NoDocument if it was deleted. Is null if the\n     * document went out of view without the server sending a new document.\n     */\n    r) {\n        this.fe = e, this.removedTargetIds = t, this.key = n, this.ge = r;\n    }\n}\n\nclass __PRIVATE_ExistenceFilterChange {\n    constructor(e, t) {\n        this.targetId = e, this.pe = t;\n    }\n}\n\nclass __PRIVATE_WatchTargetChange {\n    constructor(\n    /** What kind of change occurred to the watch target. */\n    e, \n    /** The target IDs that were added/removed/set. */\n    t, \n    /**\n     * An opaque, server-assigned token that allows watching a target to be\n     * resumed after disconnecting without retransmitting all the data that\n     * matches the target. The resume token essentially identifies a point in\n     * time from which the server should resume sending results.\n     */\n    n = ByteString.EMPTY_BYTE_STRING\n    /** An RPC error indicating why the watch failed. */ , r = null) {\n        this.state = e, this.targetIds = t, this.resumeToken = n, this.cause = r;\n    }\n}\n\n/** Tracks the internal state of a Watch target. */ class __PRIVATE_TargetState {\n    constructor() {\n        /**\n         * The number of pending responses (adds or removes) that we are waiting on.\n         * We only consider targets active that have no pending responses.\n         */\n        this.ye = 0, \n        /**\n         * Keeps track of the document changes since the last raised snapshot.\n         *\n         * These changes are continuously updated as we receive document updates and\n         * always reflect the current set of changes against the last issued snapshot.\n         */\n        this.we = __PRIVATE_snapshotChangesMap(), \n        /** See public getters for explanations of these fields. */\n        this.Se = ByteString.EMPTY_BYTE_STRING, this.be = !1, \n        /**\n         * Whether this target state should be included in the next snapshot. We\n         * initialize to true so that newly-added targets are included in the next\n         * RemoteEvent.\n         */\n        this.De = !0;\n    }\n    /**\n     * Whether this target has been marked 'current'.\n     *\n     * 'Current' has special meaning in the RPC protocol: It implies that the\n     * Watch backend has sent us all changes up to the point at which the target\n     * was added and that the target is consistent with the rest of the watch\n     * stream.\n     */    get current() {\n        return this.be;\n    }\n    /** The last resume token sent to us for this target. */    get resumeToken() {\n        return this.Se;\n    }\n    /** Whether this target has pending target adds or target removes. */    get ve() {\n        return 0 !== this.ye;\n    }\n    /** Whether we have modified any state that should trigger a snapshot. */    get Ce() {\n        return this.De;\n    }\n    /**\n     * Applies the resume token to the TargetChange, but only when it has a new\n     * value. Empty resumeTokens are discarded.\n     */    Fe(e) {\n        e.approximateByteSize() > 0 && (this.De = !0, this.Se = e);\n    }\n    /**\n     * Creates a target change from the current set of changes.\n     *\n     * To reset the document changes after raising this snapshot, call\n     * `clearPendingChanges()`.\n     */    Me() {\n        let e = __PRIVATE_documentKeySet(), t = __PRIVATE_documentKeySet(), n = __PRIVATE_documentKeySet();\n        return this.we.forEach(((r, i) => {\n            switch (i) {\n              case 0 /* ChangeType.Added */ :\n                e = e.add(r);\n                break;\n\n              case 2 /* ChangeType.Modified */ :\n                t = t.add(r);\n                break;\n\n              case 1 /* ChangeType.Removed */ :\n                n = n.add(r);\n                break;\n\n              default:\n                fail();\n            }\n        })), new TargetChange(this.Se, this.be, e, t, n);\n    }\n    /**\n     * Resets the document changes and sets `hasPendingChanges` to false.\n     */    xe() {\n        this.De = !1, this.we = __PRIVATE_snapshotChangesMap();\n    }\n    Oe(e, t) {\n        this.De = !0, this.we = this.we.insert(e, t);\n    }\n    Ne(e) {\n        this.De = !0, this.we = this.we.remove(e);\n    }\n    Be() {\n        this.ye += 1;\n    }\n    Le() {\n        this.ye -= 1;\n    }\n    ke() {\n        this.De = !0, this.be = !0;\n    }\n}\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nclass __PRIVATE_WatchChangeAggregator {\n    constructor(e) {\n        this.qe = e, \n        /** The internal state of all tracked targets. */\n        this.Qe = new Map, \n        /** Keeps track of the documents to update since the last raised snapshot. */\n        this.Ke = __PRIVATE_mutableDocumentMap(), \n        /** A mapping of document keys to their set of target IDs. */\n        this.$e = __PRIVATE_documentTargetMap(), \n        /**\n         * A map of targets with existence filter mismatches. These targets are\n         * known to be inconsistent and their listens needs to be re-established by\n         * RemoteStore.\n         */\n        this.Ue = new SortedMap(__PRIVATE_primitiveComparator);\n    }\n    /**\n     * Processes and adds the DocumentWatchChange to the current set of changes.\n     */    We(e) {\n        for (const t of e.fe) e.ge && e.ge.isFoundDocument() ? this.Ge(t, e.ge) : this.ze(t, e.key, e.ge);\n        for (const t of e.removedTargetIds) this.ze(t, e.key, e.ge);\n    }\n    /** Processes and adds the WatchTargetChange to the current set of changes. */    je(e) {\n        this.forEachTarget(e, (t => {\n            const n = this.He(t);\n            switch (e.state) {\n              case 0 /* WatchTargetChangeState.NoChange */ :\n                this.Je(t) && n.Fe(e.resumeToken);\n                break;\n\n              case 1 /* WatchTargetChangeState.Added */ :\n                // We need to decrement the number of pending acks needed from watch\n                // for this targetId.\n                n.Le(), n.ve || \n                // We have a freshly added target, so we need to reset any state\n                // that we had previously. This can happen e.g. when remove and add\n                // back a target for existence filter mismatches.\n                n.xe(), n.Fe(e.resumeToken);\n                break;\n\n              case 2 /* WatchTargetChangeState.Removed */ :\n                // We need to keep track of removed targets to we can post-filter and\n                // remove any target changes.\n                // We need to decrement the number of pending acks needed from watch\n                // for this targetId.\n                n.Le(), n.ve || this.removeTarget(t);\n                break;\n\n              case 3 /* WatchTargetChangeState.Current */ :\n                this.Je(t) && (n.ke(), n.Fe(e.resumeToken));\n                break;\n\n              case 4 /* WatchTargetChangeState.Reset */ :\n                this.Je(t) && (\n                // Reset the target and synthesizes removes for all existing\n                // documents. The backend will re-add any documents that still\n                // match the target before it sends the next global snapshot.\n                this.Ye(t), n.Fe(e.resumeToken));\n                break;\n\n              default:\n                fail();\n            }\n        }));\n    }\n    /**\n     * Iterates over all targetIds that the watch change applies to: either the\n     * targetIds explicitly listed in the change or the targetIds of all currently\n     * active targets.\n     */    forEachTarget(e, t) {\n        e.targetIds.length > 0 ? e.targetIds.forEach(t) : this.Qe.forEach(((e, n) => {\n            this.Je(n) && t(n);\n        }));\n    }\n    /**\n     * Handles existence filters and synthesizes deletes for filter mismatches.\n     * Targets that are invalidated by filter mismatches are added to\n     * `pendingTargetResets`.\n     */    Ze(e) {\n        var t, n;\n        const r = e.targetId, i = e.pe.count, s = this.Xe(r);\n        if (s) {\n            const o = s.target;\n            if (__PRIVATE_targetIsDocumentTarget(o)) if (0 === i) {\n                // The existence filter told us the document does not exist. We deduce\n                // that this document does not exist and apply a deleted document to\n                // our updates. Without applying this deleted document there might be\n                // another query that will raise this document as part of a snapshot\n                // until it is resolved, essentially exposing inconsistency between\n                // queries.\n                const e = new DocumentKey(o.path);\n                this.ze(r, e, MutableDocument.newNoDocument(e, SnapshotVersion.min()));\n            } else __PRIVATE_hardAssert(1 === i); else {\n                const s = this.et(r);\n                // Existence filter mismatch. Mark the documents as being in limbo, and\n                // raise a snapshot with `isFromCache:true`.\n                                if (s !== i) {\n                    // Apply bloom filter to identify and mark removed documents.\n                    const i = this.tt(e, s);\n                    if (0 /* BloomFilterApplicationStatus.Success */ !== i.status) {\n                        // If bloom filter application fails, we reset the mapping and\n                        // trigger re-run of the query.\n                        this.Ye(r);\n                        const e = 2 /* BloomFilterApplicationStatus.FalsePositive */ === i.status ? \"TargetPurposeExistenceFilterMismatchBloom\" /* TargetPurpose.ExistenceFilterMismatchBloom */ : \"TargetPurposeExistenceFilterMismatch\" /* TargetPurpose.ExistenceFilterMismatch */;\n                        this.Ue = this.Ue.insert(r, e);\n                    }\n                    null === (t = __PRIVATE_TestingHooks.instance) || void 0 === t || t.notifyOnExistenceFilterMismatch(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e, t, n, r) {\n                        var i, s, o, _, a, u;\n                        const c = {\n                            localCacheCount: n,\n                            existenceFilterCount: r.count\n                        }, l = r.unchangedNames;\n                        l && (c.bloomFilter = {\n                            applied: 0 /* BloomFilterApplicationStatus.Success */ === e,\n                            hashCount: null !== (i = null == l ? void 0 : l.hashCount) && void 0 !== i ? i : 0,\n                            bitmapLength: null !== (_ = null === (o = null === (s = null == l ? void 0 : l.bits) || void 0 === s ? void 0 : s.bitmap) || void 0 === o ? void 0 : o.length) && void 0 !== _ ? _ : 0,\n                            padding: null !== (u = null === (a = null == l ? void 0 : l.bits) || void 0 === a ? void 0 : a.padding) && void 0 !== u ? u : 0\n                        }, t && (c.bloomFilter.mightContain = t));\n                        return c;\n                    }\n                    /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (i.status, null !== (n = i.nt) && void 0 !== n ? n : null, s, e.pe));\n                }\n            }\n        }\n    }\n    /**\n     * Apply bloom filter to remove the deleted documents, and return the\n     * application status.\n     */    tt(e, t) {\n        const {unchangedNames: n, count: r} = e.pe;\n        if (!n || !n.bits) return {\n            status: 1\n /* BloomFilterApplicationStatus.Skipped */        };\n        const {bits: {bitmap: i = \"\", padding: s = 0}, hashCount: o = 0} = n;\n        let _, a;\n        try {\n            _ = __PRIVATE_normalizeByteString(i).toUint8Array();\n        } catch (e) {\n            if (e instanceof __PRIVATE_Base64DecodeError) return __PRIVATE_logWarn(\"Decoding the base64 bloom filter in existence filter failed (\" + e.message + \"); ignoring the bloom filter and falling back to full re-query.\"), \n            {\n                status: 1\n /* BloomFilterApplicationStatus.Skipped */            };\n            throw e;\n        }\n        try {\n            // BloomFilter throws error if the inputs are invalid.\n            a = new BloomFilter(_, s, o);\n        } catch (e) {\n            return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError ? \"BloomFilter error: \" : \"Applying bloom filter failed: \", e), \n            {\n                status: 1\n /* BloomFilterApplicationStatus.Skipped */            };\n        }\n        const __PRIVATE_bloomFilterMightContain = e => {\n            const t = this.qe.rt();\n            return a.mightContain(`projects/${t.projectId}/databases/${t.database}/documents/${e}`);\n        };\n        if (0 === a.de) return {\n            status: 1\n /* BloomFilterApplicationStatus.Skipped */        };\n        return {\n            status: r === t - this.it(e.targetId, __PRIVATE_bloomFilterMightContain) ? 0 /* BloomFilterApplicationStatus.Success */ : 2 /* BloomFilterApplicationStatus.FalsePositive */ ,\n            nt: __PRIVATE_bloomFilterMightContain\n        };\n    }\n    /**\n     * Filter out removed documents based on bloom filter membership result and\n     * return number of documents removed.\n     */    it(e, t) {\n        const n = this.qe.getRemoteKeysForTarget(e);\n        let r = 0;\n        return n.forEach((n => {\n            t(n.path.canonicalString()) || (this.ze(e, n, /*updatedDocument=*/ null), r++);\n        })), r;\n    }\n    /**\n     * Converts the currently accumulated state into a remote event at the\n     * provided snapshot version. Resets the accumulated changes before returning.\n     */    st(e) {\n        const t = new Map;\n        this.Qe.forEach(((n, r) => {\n            const i = this.Xe(r);\n            if (i) {\n                if (n.current && __PRIVATE_targetIsDocumentTarget(i.target)) {\n                    // Document queries for document that don't exist can produce an empty\n                    // result set. To update our local cache, we synthesize a document\n                    // delete if we have not previously received the document. This\n                    // resolves the limbo state of the document, removing it from\n                    // limboDocumentRefs.\n                    // TODO(dimond): Ideally we would have an explicit lookup target\n                    // instead resulting in an explicit delete message and we could\n                    // remove this special logic.\n                    const t = new DocumentKey(i.target.path);\n                    null !== this.Ke.get(t) || this.ot(r, t) || this.ze(r, t, MutableDocument.newNoDocument(t, e));\n                }\n                n.Ce && (t.set(r, n.Me()), n.xe());\n            }\n        }));\n        let n = __PRIVATE_documentKeySet();\n        // We extract the set of limbo-only document updates as the GC logic\n        // special-cases documents that do not appear in the target cache.\n        \n        // TODO(gsoltis): Expand on this comment once GC is available in the JS\n        // client.\n                this.$e.forEach(((e, t) => {\n            let r = !0;\n            t.forEachWhile((e => {\n                const t = this.Xe(e);\n                return !t || \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ === t.purpose || (r = !1, \n                !1);\n            })), r && (n = n.add(e));\n        })), this.Ke.forEach(((t, n) => n.setReadTime(e)));\n        const r = new RemoteEvent(e, t, this.Ue, this.Ke, n);\n        return this.Ke = __PRIVATE_mutableDocumentMap(), this.$e = __PRIVATE_documentTargetMap(), \n        this.Ue = new SortedMap(__PRIVATE_primitiveComparator), r;\n    }\n    /**\n     * Adds the provided document to the internal list of document updates and\n     * its document key to the given target's mapping.\n     */\n    // Visible for testing.\n    Ge(e, t) {\n        if (!this.Je(e)) return;\n        const n = this.ot(e, t.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;\n        this.He(e).Oe(t.key, n), this.Ke = this.Ke.insert(t.key, t), this.$e = this.$e.insert(t.key, this._t(t.key).add(e));\n    }\n    /**\n     * Removes the provided document from the target mapping. If the\n     * document no longer matches the target, but the document's state is still\n     * known (e.g. we know that the document was deleted or we received the change\n     * that caused the filter mismatch), the new document can be provided\n     * to update the remote document cache.\n     */\n    // Visible for testing.\n    ze(e, t, n) {\n        if (!this.Je(e)) return;\n        const r = this.He(e);\n        this.ot(e, t) ? r.Oe(t, 1 /* ChangeType.Removed */) : \n        // The document may have entered and left the target before we raised a\n        // snapshot, so we can just ignore the change.\n        r.Ne(t), this.$e = this.$e.insert(t, this._t(t).delete(e)), n && (this.Ke = this.Ke.insert(t, n));\n    }\n    removeTarget(e) {\n        this.Qe.delete(e);\n    }\n    /**\n     * Returns the current count of documents in the target. This includes both\n     * the number of documents that the LocalStore considers to be part of the\n     * target as well as any accumulated changes.\n     */    et(e) {\n        const t = this.He(e).Me();\n        return this.qe.getRemoteKeysForTarget(e).size + t.addedDocuments.size - t.removedDocuments.size;\n    }\n    /**\n     * Increment the number of acks needed from watch before we can consider the\n     * server to be 'in-sync' with the client's active targets.\n     */    Be(e) {\n        this.He(e).Be();\n    }\n    He(e) {\n        let t = this.Qe.get(e);\n        return t || (t = new __PRIVATE_TargetState, this.Qe.set(e, t)), t;\n    }\n    _t(e) {\n        let t = this.$e.get(e);\n        return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.$e = this.$e.insert(e, t)), \n        t;\n    }\n    /**\n     * Verifies that the user is still interested in this target (by calling\n     * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n     * from watch.\n     */    Je(e) {\n        const t = null !== this.Xe(e);\n        return t || __PRIVATE_logDebug(\"WatchChangeAggregator\", \"Detected inactive target\", e), \n        t;\n    }\n    /**\n     * Returns the TargetData for an active target (i.e. a target that the user\n     * is still interested in that has no outstanding target change requests).\n     */    Xe(e) {\n        const t = this.Qe.get(e);\n        return t && t.ve ? null : this.qe.ut(e);\n    }\n    /**\n     * Resets the state of a Watch target to its initial state (e.g. sets\n     * 'current' to false, clears the resume token and removes its target mapping\n     * from all documents).\n     */    Ye(e) {\n        this.Qe.set(e, new __PRIVATE_TargetState);\n        this.qe.getRemoteKeysForTarget(e).forEach((t => {\n            this.ze(e, t, /*updatedDocument=*/ null);\n        }));\n    }\n    /**\n     * Returns whether the LocalStore considers the document to be part of the\n     * specified target.\n     */    ot(e, t) {\n        return this.qe.getRemoteKeysForTarget(e).has(t);\n    }\n}\n\nfunction __PRIVATE_documentTargetMap() {\n    return new SortedMap(DocumentKey.comparator);\n}\n\nfunction __PRIVATE_snapshotChangesMap() {\n    return new SortedMap(DocumentKey.comparator);\n}\n\nconst Pe = (() => {\n    const e = {\n        asc: \"ASCENDING\",\n        desc: \"DESCENDING\"\n    };\n    return e;\n})(), Ie = (() => {\n    const e = {\n        \"<\": \"LESS_THAN\",\n        \"<=\": \"LESS_THAN_OR_EQUAL\",\n        \">\": \"GREATER_THAN\",\n        \">=\": \"GREATER_THAN_OR_EQUAL\",\n        \"==\": \"EQUAL\",\n        \"!=\": \"NOT_EQUAL\",\n        \"array-contains\": \"ARRAY_CONTAINS\",\n        in: \"IN\",\n        \"not-in\": \"NOT_IN\",\n        \"array-contains-any\": \"ARRAY_CONTAINS_ANY\"\n    };\n    return e;\n})(), Te = (() => {\n    const e = {\n        and: \"AND\",\n        or: \"OR\"\n    };\n    return e;\n})();\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nclass JsonProtoSerializer {\n    constructor(e, t) {\n        this.databaseId = e, this.useProto3Json = t;\n    }\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: <number> } struct.\n */\nfunction __PRIVATE_toInt32Proto(e, t) {\n    return e.useProto3Json || __PRIVATE_isNullOrUndefined(t) ? t : {\n        value: t\n    };\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nfunction toTimestamp(e, t) {\n    if (e.useProto3Json) {\n        return `${new Date(1e3 * t.seconds).toISOString().replace(/\\.\\d*/, \"\").replace(\"Z\", \"\")}.${(\"000000000\" + t.nanoseconds).slice(-9)}Z`;\n    }\n    return {\n        seconds: \"\" + t.seconds,\n        nanos: t.nanoseconds\n    };\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nfunction __PRIVATE_toBytes(e, t) {\n    return e.useProto3Json ? t.toBase64() : t.toUint8Array();\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */ function __PRIVATE_toVersion(e, t) {\n    return toTimestamp(e, t.toTimestamp());\n}\n\nfunction __PRIVATE_fromVersion(e) {\n    return __PRIVATE_hardAssert(!!e), SnapshotVersion.fromTimestamp(function fromTimestamp(e) {\n        const t = __PRIVATE_normalizeTimestamp(e);\n        return new Timestamp(t.seconds, t.nanos);\n    }(e));\n}\n\nfunction __PRIVATE_toResourceName(e, t) {\n    return function __PRIVATE_fullyQualifiedPrefixPath(e) {\n        return new ResourcePath([ \"projects\", e.projectId, \"databases\", e.database ]);\n    }(e).child(\"documents\").child(t).canonicalString();\n}\n\nfunction __PRIVATE_fromResourceName(e) {\n    const t = ResourcePath.fromString(e);\n    return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t)), t;\n}\n\nfunction __PRIVATE_toName(e, t) {\n    return __PRIVATE_toResourceName(e.databaseId, t.path);\n}\n\nfunction fromName(e, t) {\n    const n = __PRIVATE_fromResourceName(t);\n    if (n.get(1) !== e.databaseId.projectId) throw new FirestoreError(v.INVALID_ARGUMENT, \"Tried to deserialize key from different project: \" + n.get(1) + \" vs \" + e.databaseId.projectId);\n    if (n.get(3) !== e.databaseId.database) throw new FirestoreError(v.INVALID_ARGUMENT, \"Tried to deserialize key from different database: \" + n.get(3) + \" vs \" + e.databaseId.database);\n    return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(n));\n}\n\nfunction __PRIVATE_toQueryPath(e, t) {\n    return __PRIVATE_toResourceName(e.databaseId, t);\n}\n\nfunction __PRIVATE_fromQueryPath(e) {\n    const t = __PRIVATE_fromResourceName(e);\n    // In v1beta1 queries for collections at the root did not have a trailing\n    // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n    // ability to read the v1beta1 form for compatibility with queries persisted\n    // in the local target cache.\n        return 4 === t.length ? ResourcePath.emptyPath() : __PRIVATE_extractLocalPathFromResourceName(t);\n}\n\nfunction __PRIVATE_getEncodedDatabaseId(e) {\n    return new ResourcePath([ \"projects\", e.databaseId.projectId, \"databases\", e.databaseId.database ]).canonicalString();\n}\n\nfunction __PRIVATE_extractLocalPathFromResourceName(e) {\n    return __PRIVATE_hardAssert(e.length > 4 && \"documents\" === e.get(4)), e.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */ function __PRIVATE_toMutationDocument(e, t, n) {\n    return {\n        name: __PRIVATE_toName(e, t),\n        fields: n.value.mapValue.fields\n    };\n}\n\nfunction __PRIVATE_fromDocument(e, t, n) {\n    const r = fromName(e, t.name), i = __PRIVATE_fromVersion(t.updateTime), s = t.createTime ? __PRIVATE_fromVersion(t.createTime) : SnapshotVersion.min(), o = new ObjectValue({\n        mapValue: {\n            fields: t.fields\n        }\n    }), _ = MutableDocument.newFoundDocument(r, i, s, o);\n    return n && _.setHasCommittedMutations(), n ? _.setHasCommittedMutations() : _;\n}\n\nfunction __PRIVATE_fromBatchGetDocumentsResponse(e, t) {\n    return \"found\" in t ? function __PRIVATE_fromFound(e, t) {\n        __PRIVATE_hardAssert(!!t.found), t.found.name, t.found.updateTime;\n        const n = fromName(e, t.found.name), r = __PRIVATE_fromVersion(t.found.updateTime), i = t.found.createTime ? __PRIVATE_fromVersion(t.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({\n            mapValue: {\n                fields: t.found.fields\n            }\n        });\n        return MutableDocument.newFoundDocument(n, r, i, s);\n    }(e, t) : \"missing\" in t ? function __PRIVATE_fromMissing(e, t) {\n        __PRIVATE_hardAssert(!!t.missing), __PRIVATE_hardAssert(!!t.readTime);\n        const n = fromName(e, t.missing), r = __PRIVATE_fromVersion(t.readTime);\n        return MutableDocument.newNoDocument(n, r);\n    }(e, t) : fail();\n}\n\nfunction __PRIVATE_fromWatchChange(e, t) {\n    let n;\n    if (\"targetChange\" in t) {\n        t.targetChange;\n        // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n        // if unset\n        const r = function __PRIVATE_fromWatchTargetChangeState(e) {\n            return \"NO_CHANGE\" === e ? 0 /* WatchTargetChangeState.NoChange */ : \"ADD\" === e ? 1 /* WatchTargetChangeState.Added */ : \"REMOVE\" === e ? 2 /* WatchTargetChangeState.Removed */ : \"CURRENT\" === e ? 3 /* WatchTargetChangeState.Current */ : \"RESET\" === e ? 4 /* WatchTargetChangeState.Reset */ : fail();\n        }(t.targetChange.targetChangeType || \"NO_CHANGE\"), i = t.targetChange.targetIds || [], s = function __PRIVATE_fromBytes(e, t) {\n            return e.useProto3Json ? (__PRIVATE_hardAssert(void 0 === t || \"string\" == typeof t), \n            ByteString.fromBase64String(t || \"\")) : (__PRIVATE_hardAssert(void 0 === t || t instanceof Uint8Array), \n            ByteString.fromUint8Array(t || new Uint8Array));\n        }(e, t.targetChange.resumeToken), o = t.targetChange.cause, _ = o && function __PRIVATE_fromRpcStatus(e) {\n            const t = void 0 === e.code ? v.UNKNOWN : __PRIVATE_mapCodeFromRpcCode(e.code);\n            return new FirestoreError(t, e.message || \"\");\n        }(o);\n        n = new __PRIVATE_WatchTargetChange(r, i, s, _ || null);\n    } else if (\"documentChange\" in t) {\n        t.documentChange;\n        const r = t.documentChange;\n        r.document, r.document.name, r.document.updateTime;\n        const i = fromName(e, r.document.name), s = __PRIVATE_fromVersion(r.document.updateTime), o = r.document.createTime ? __PRIVATE_fromVersion(r.document.createTime) : SnapshotVersion.min(), _ = new ObjectValue({\n            mapValue: {\n                fields: r.document.fields\n            }\n        }), a = MutableDocument.newFoundDocument(i, s, o, _), u = r.targetIds || [], c = r.removedTargetIds || [];\n        n = new __PRIVATE_DocumentWatchChange(u, c, a.key, a);\n    } else if (\"documentDelete\" in t) {\n        t.documentDelete;\n        const r = t.documentDelete;\n        r.document;\n        const i = fromName(e, r.document), s = r.readTime ? __PRIVATE_fromVersion(r.readTime) : SnapshotVersion.min(), o = MutableDocument.newNoDocument(i, s), _ = r.removedTargetIds || [];\n        n = new __PRIVATE_DocumentWatchChange([], _, o.key, o);\n    } else if (\"documentRemove\" in t) {\n        t.documentRemove;\n        const r = t.documentRemove;\n        r.document;\n        const i = fromName(e, r.document), s = r.removedTargetIds || [];\n        n = new __PRIVATE_DocumentWatchChange([], s, i, null);\n    } else {\n        if (!(\"filter\" in t)) return fail();\n        {\n            t.filter;\n            const e = t.filter;\n            e.targetId;\n            const {count: r = 0, unchangedNames: i} = e, s = new ExistenceFilter(r, i), o = e.targetId;\n            n = new __PRIVATE_ExistenceFilterChange(o, s);\n        }\n    }\n    return n;\n}\n\nfunction toMutation(e, t) {\n    let n;\n    if (t instanceof __PRIVATE_SetMutation) n = {\n        update: __PRIVATE_toMutationDocument(e, t.key, t.value)\n    }; else if (t instanceof __PRIVATE_DeleteMutation) n = {\n        delete: __PRIVATE_toName(e, t.key)\n    }; else if (t instanceof __PRIVATE_PatchMutation) n = {\n        update: __PRIVATE_toMutationDocument(e, t.key, t.data),\n        updateMask: __PRIVATE_toDocumentMask(t.fieldMask)\n    }; else {\n        if (!(t instanceof __PRIVATE_VerifyMutation)) return fail();\n        n = {\n            verify: __PRIVATE_toName(e, t.key)\n        };\n    }\n    return t.fieldTransforms.length > 0 && (n.updateTransforms = t.fieldTransforms.map((e => function __PRIVATE_toFieldTransform(e, t) {\n        const n = t.transform;\n        if (n instanceof __PRIVATE_ServerTimestampTransform) return {\n            fieldPath: t.field.canonicalString(),\n            setToServerValue: \"REQUEST_TIME\"\n        };\n        if (n instanceof __PRIVATE_ArrayUnionTransformOperation) return {\n            fieldPath: t.field.canonicalString(),\n            appendMissingElements: {\n                values: n.elements\n            }\n        };\n        if (n instanceof __PRIVATE_ArrayRemoveTransformOperation) return {\n            fieldPath: t.field.canonicalString(),\n            removeAllFromArray: {\n                values: n.elements\n            }\n        };\n        if (n instanceof __PRIVATE_NumericIncrementTransformOperation) return {\n            fieldPath: t.field.canonicalString(),\n            increment: n.Te\n        };\n        throw fail();\n    }(0, e)))), t.precondition.isNone || (n.currentDocument = function __PRIVATE_toPrecondition(e, t) {\n        return void 0 !== t.updateTime ? {\n            updateTime: __PRIVATE_toVersion(e, t.updateTime)\n        } : void 0 !== t.exists ? {\n            exists: t.exists\n        } : fail();\n    }(e, t.precondition)), n;\n}\n\nfunction __PRIVATE_fromMutation(e, t) {\n    const n = t.currentDocument ? function __PRIVATE_fromPrecondition(e) {\n        return void 0 !== e.updateTime ? Precondition.updateTime(__PRIVATE_fromVersion(e.updateTime)) : void 0 !== e.exists ? Precondition.exists(e.exists) : Precondition.none();\n    }(t.currentDocument) : Precondition.none(), r = t.updateTransforms ? t.updateTransforms.map((t => function __PRIVATE_fromFieldTransform(e, t) {\n        let n = null;\n        if (\"setToServerValue\" in t) __PRIVATE_hardAssert(\"REQUEST_TIME\" === t.setToServerValue), \n        n = new __PRIVATE_ServerTimestampTransform; else if (\"appendMissingElements\" in t) {\n            const e = t.appendMissingElements.values || [];\n            n = new __PRIVATE_ArrayUnionTransformOperation(e);\n        } else if (\"removeAllFromArray\" in t) {\n            const e = t.removeAllFromArray.values || [];\n            n = new __PRIVATE_ArrayRemoveTransformOperation(e);\n        } else \"increment\" in t ? n = new __PRIVATE_NumericIncrementTransformOperation(e, t.increment) : fail();\n        const r = FieldPath$1.fromServerFormat(t.fieldPath);\n        return new FieldTransform(r, n);\n    }(e, t))) : [];\n    if (t.update) {\n        t.update.name;\n        const i = fromName(e, t.update.name), s = new ObjectValue({\n            mapValue: {\n                fields: t.update.fields\n            }\n        });\n        if (t.updateMask) {\n            const e = function __PRIVATE_fromDocumentMask(e) {\n                const t = e.fieldPaths || [];\n                return new FieldMask(t.map((e => FieldPath$1.fromServerFormat(e))));\n            }(t.updateMask);\n            return new __PRIVATE_PatchMutation(i, s, e, n, r);\n        }\n        return new __PRIVATE_SetMutation(i, s, n, r);\n    }\n    if (t.delete) {\n        const r = fromName(e, t.delete);\n        return new __PRIVATE_DeleteMutation(r, n);\n    }\n    if (t.verify) {\n        const r = fromName(e, t.verify);\n        return new __PRIVATE_VerifyMutation(r, n);\n    }\n    return fail();\n}\n\nfunction __PRIVATE_fromWriteResults(e, t) {\n    return e && e.length > 0 ? (__PRIVATE_hardAssert(void 0 !== t), e.map((e => function __PRIVATE_fromWriteResult(e, t) {\n        // NOTE: Deletes don't have an updateTime.\n        let n = e.updateTime ? __PRIVATE_fromVersion(e.updateTime) : __PRIVATE_fromVersion(t);\n        return n.isEqual(SnapshotVersion.min()) && (\n        // The Firestore Emulator currently returns an update time of 0 for\n        // deletes of non-existing documents (rather than null). This breaks the\n        // test \"get deleted doc while offline with source=cache\" as NoDocuments\n        // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n        // TODO(#2149): Remove this when Emulator is fixed\n        n = __PRIVATE_fromVersion(t)), new MutationResult(n, e.transformResults || []);\n    }(e, t)))) : [];\n}\n\nfunction __PRIVATE_toDocumentsTarget(e, t) {\n    return {\n        documents: [ __PRIVATE_toQueryPath(e, t.path) ]\n    };\n}\n\nfunction __PRIVATE_toQueryTarget(e, t) {\n    // Dissect the path into parent, collectionId, and optional key filter.\n    const n = {\n        structuredQuery: {}\n    }, r = t.path;\n    null !== t.collectionGroup ? (n.parent = __PRIVATE_toQueryPath(e, r), n.structuredQuery.from = [ {\n        collectionId: t.collectionGroup,\n        allDescendants: !0\n    } ]) : (n.parent = __PRIVATE_toQueryPath(e, r.popLast()), n.structuredQuery.from = [ {\n        collectionId: r.lastSegment()\n    } ]);\n    const i = function __PRIVATE_toFilters(e) {\n        if (0 === e.length) return;\n        return __PRIVATE_toFilter(CompositeFilter.create(e, \"and\" /* CompositeOperator.AND */));\n    }(t.filters);\n    i && (n.structuredQuery.where = i);\n    const s = function __PRIVATE_toOrder(e) {\n        if (0 === e.length) return;\n        return e.map((e => \n        // visible for testing\n        function __PRIVATE_toPropertyOrder(e) {\n            return {\n                field: __PRIVATE_toFieldPathReference(e.field),\n                direction: __PRIVATE_toDirection(e.dir)\n            };\n        }(e)));\n    }(t.orderBy);\n    s && (n.structuredQuery.orderBy = s);\n    const o = __PRIVATE_toInt32Proto(e, t.limit);\n    return null !== o && (n.structuredQuery.limit = o), t.startAt && (n.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(e) {\n        return {\n            before: e.inclusive,\n            values: e.position\n        };\n    }(t.startAt)), t.endAt && (n.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(e) {\n        return {\n            before: !e.inclusive,\n            values: e.position\n        };\n    }(t.endAt)), n;\n}\n\nfunction __PRIVATE_convertQueryTargetToQuery(e) {\n    let t = __PRIVATE_fromQueryPath(e.parent);\n    const n = e.structuredQuery, r = n.from ? n.from.length : 0;\n    let i = null;\n    if (r > 0) {\n        __PRIVATE_hardAssert(1 === r);\n        const e = n.from[0];\n        e.allDescendants ? i = e.collectionId : t = t.child(e.collectionId);\n    }\n    let s = [];\n    n.where && (s = function __PRIVATE_fromFilters(e) {\n        const t = __PRIVATE_fromFilter(e);\n        if (t instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(t)) return t.getFilters();\n        return [ t ];\n    }(n.where));\n    let o = [];\n    n.orderBy && (o = function __PRIVATE_fromOrder(e) {\n        return e.map((e => function __PRIVATE_fromPropertyOrder(e) {\n            return new OrderBy(__PRIVATE_fromFieldPathReference(e.field), \n            // visible for testing\n            function __PRIVATE_fromDirection(e) {\n                switch (e) {\n                  case \"ASCENDING\":\n                    return \"asc\" /* Direction.ASCENDING */;\n\n                  case \"DESCENDING\":\n                    return \"desc\" /* Direction.DESCENDING */;\n\n                  default:\n                    return;\n                }\n            }\n            // visible for testing\n            (e.direction));\n        }\n        // visible for testing\n        (e)));\n    }(n.orderBy));\n    let _ = null;\n    n.limit && (_ = function __PRIVATE_fromInt32Proto(e) {\n        let t;\n        return t = \"object\" == typeof e ? e.value : e, __PRIVATE_isNullOrUndefined(t) ? null : t;\n    }(n.limit));\n    let a = null;\n    n.startAt && (a = function __PRIVATE_fromStartAtCursor(e) {\n        const t = !!e.before, n = e.values || [];\n        return new Bound(n, t);\n    }(n.startAt));\n    let u = null;\n    return n.endAt && (u = function __PRIVATE_fromEndAtCursor(e) {\n        const t = !e.before, n = e.values || [];\n        return new Bound(n, t);\n    }\n    // visible for testing\n    (n.endAt)), __PRIVATE_newQuery(t, i, o, s, _, \"F\" /* LimitType.First */ , a, u);\n}\n\nfunction __PRIVATE_toListenRequestLabels(e, t) {\n    const n = function __PRIVATE_toLabel(e) {\n        switch (e) {\n          case \"TargetPurposeListen\" /* TargetPurpose.Listen */ :\n            return null;\n\n          case \"TargetPurposeExistenceFilterMismatch\" /* TargetPurpose.ExistenceFilterMismatch */ :\n            return \"existence-filter-mismatch\";\n\n          case \"TargetPurposeExistenceFilterMismatchBloom\" /* TargetPurpose.ExistenceFilterMismatchBloom */ :\n            return \"existence-filter-mismatch-bloom\";\n\n          case \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ :\n            return \"limbo-document\";\n\n          default:\n            return fail();\n        }\n    }(t.purpose);\n    return null == n ? null : {\n        \"goog-listen-tags\": n\n    };\n}\n\nfunction __PRIVATE_fromFilter(e) {\n    return void 0 !== e.unaryFilter ? function __PRIVATE_fromUnaryFilter(e) {\n        switch (e.unaryFilter.op) {\n          case \"IS_NAN\":\n            const t = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n            return FieldFilter.create(t, \"==\" /* Operator.EQUAL */ , {\n                doubleValue: NaN\n            });\n\n          case \"IS_NULL\":\n            const n = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n            return FieldFilter.create(n, \"==\" /* Operator.EQUAL */ , {\n                nullValue: \"NULL_VALUE\"\n            });\n\n          case \"IS_NOT_NAN\":\n            const r = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n            return FieldFilter.create(r, \"!=\" /* Operator.NOT_EQUAL */ , {\n                doubleValue: NaN\n            });\n\n          case \"IS_NOT_NULL\":\n            const i = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);\n            return FieldFilter.create(i, \"!=\" /* Operator.NOT_EQUAL */ , {\n                nullValue: \"NULL_VALUE\"\n            });\n\n          default:\n            return fail();\n        }\n    }(e) : void 0 !== e.fieldFilter ? function __PRIVATE_fromFieldFilter(e) {\n        return FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field), function __PRIVATE_fromOperatorName(e) {\n            switch (e) {\n              case \"EQUAL\":\n                return \"==\" /* Operator.EQUAL */;\n\n              case \"NOT_EQUAL\":\n                return \"!=\" /* Operator.NOT_EQUAL */;\n\n              case \"GREATER_THAN\":\n                return \">\" /* Operator.GREATER_THAN */;\n\n              case \"GREATER_THAN_OR_EQUAL\":\n                return \">=\" /* Operator.GREATER_THAN_OR_EQUAL */;\n\n              case \"LESS_THAN\":\n                return \"<\" /* Operator.LESS_THAN */;\n\n              case \"LESS_THAN_OR_EQUAL\":\n                return \"<=\" /* Operator.LESS_THAN_OR_EQUAL */;\n\n              case \"ARRAY_CONTAINS\":\n                return \"array-contains\" /* Operator.ARRAY_CONTAINS */;\n\n              case \"IN\":\n                return \"in\" /* Operator.IN */;\n\n              case \"NOT_IN\":\n                return \"not-in\" /* Operator.NOT_IN */;\n\n              case \"ARRAY_CONTAINS_ANY\":\n                return \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */;\n\n              default:\n                return fail();\n            }\n        }(e.fieldFilter.op), e.fieldFilter.value);\n    }(e) : void 0 !== e.compositeFilter ? function __PRIVATE_fromCompositeFilter(e) {\n        return CompositeFilter.create(e.compositeFilter.filters.map((e => __PRIVATE_fromFilter(e))), function __PRIVATE_fromCompositeOperatorName(e) {\n            switch (e) {\n              case \"AND\":\n                return \"and\" /* CompositeOperator.AND */;\n\n              case \"OR\":\n                return \"or\" /* CompositeOperator.OR */;\n\n              default:\n                return fail();\n            }\n        }(e.compositeFilter.op));\n    }(e) : fail();\n}\n\nfunction __PRIVATE_toDirection(e) {\n    return Pe[e];\n}\n\nfunction __PRIVATE_toOperatorName(e) {\n    return Ie[e];\n}\n\nfunction __PRIVATE_toCompositeOperatorName(e) {\n    return Te[e];\n}\n\nfunction __PRIVATE_toFieldPathReference(e) {\n    return {\n        fieldPath: e.canonicalString()\n    };\n}\n\nfunction __PRIVATE_fromFieldPathReference(e) {\n    return FieldPath$1.fromServerFormat(e.fieldPath);\n}\n\nfunction __PRIVATE_toFilter(e) {\n    return e instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(e) {\n        if (\"==\" /* Operator.EQUAL */ === e.op) {\n            if (__PRIVATE_isNanValue(e.value)) return {\n                unaryFilter: {\n                    field: __PRIVATE_toFieldPathReference(e.field),\n                    op: \"IS_NAN\"\n                }\n            };\n            if (__PRIVATE_isNullValue(e.value)) return {\n                unaryFilter: {\n                    field: __PRIVATE_toFieldPathReference(e.field),\n                    op: \"IS_NULL\"\n                }\n            };\n        } else if (\"!=\" /* Operator.NOT_EQUAL */ === e.op) {\n            if (__PRIVATE_isNanValue(e.value)) return {\n                unaryFilter: {\n                    field: __PRIVATE_toFieldPathReference(e.field),\n                    op: \"IS_NOT_NAN\"\n                }\n            };\n            if (__PRIVATE_isNullValue(e.value)) return {\n                unaryFilter: {\n                    field: __PRIVATE_toFieldPathReference(e.field),\n                    op: \"IS_NOT_NULL\"\n                }\n            };\n        }\n        return {\n            fieldFilter: {\n                field: __PRIVATE_toFieldPathReference(e.field),\n                op: __PRIVATE_toOperatorName(e.op),\n                value: e.value\n            }\n        };\n    }(e) : e instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(e) {\n        const t = e.getFilters().map((e => __PRIVATE_toFilter(e)));\n        if (1 === t.length) return t[0];\n        return {\n            compositeFilter: {\n                op: __PRIVATE_toCompositeOperatorName(e.op),\n                filters: t\n            }\n        };\n    }(e) : fail();\n}\n\nfunction __PRIVATE_toDocumentMask(e) {\n    const t = [];\n    return e.fields.forEach((e => t.push(e.canonicalString()))), {\n        fieldPaths: t\n    };\n}\n\nfunction __PRIVATE_isValidResourceName(e) {\n    // Resource names have at least 4 components (project ID, database ID)\n    return e.length >= 4 && \"projects\" === e.get(0) && \"databases\" === e.get(2);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */ class TargetData {\n    constructor(\n    /** The target being listened to. */\n    e, \n    /**\n     * The target ID to which the target corresponds; Assigned by the\n     * LocalStore for user listens and by the SyncEngine for limbo watches.\n     */\n    t, \n    /** The purpose of the target. */\n    n, \n    /**\n     * The sequence number of the last transaction during which this target data\n     * was modified.\n     */\n    r, \n    /** The latest snapshot version seen for this target. */\n    i = SnapshotVersion.min()\n    /**\n     * The maximum snapshot version at which the associated view\n     * contained no limbo documents.\n     */ , s = SnapshotVersion.min()\n    /**\n     * An opaque, server-assigned token that allows watching a target to be\n     * resumed after disconnecting without retransmitting all the data that\n     * matches the target. The resume token essentially identifies a point in\n     * time from which the server should resume sending results.\n     */ , o = ByteString.EMPTY_BYTE_STRING\n    /**\n     * The number of documents that last matched the query at the resume token or\n     * read time. Documents are counted only when making a listen request with\n     * resume token or read time, otherwise, keep it null.\n     */ , _ = null) {\n        this.target = e, this.targetId = t, this.purpose = n, this.sequenceNumber = r, this.snapshotVersion = i, \n        this.lastLimboFreeSnapshotVersion = s, this.resumeToken = o, this.expectedCount = _;\n    }\n    /** Creates a new target data instance with an updated sequence number. */    withSequenceNumber(e) {\n        return new TargetData(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);\n    }\n    /**\n     * Creates a new target data instance with an updated resume token and\n     * snapshot version.\n     */    withResumeToken(e, t) {\n        return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, t, this.lastLimboFreeSnapshotVersion, e, \n        /* expectedCount= */ null);\n    }\n    /**\n     * Creates a new target data instance with an updated expected count.\n     */    withExpectedCount(e) {\n        return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e);\n    }\n    /**\n     * Creates a new target data instance with an updated last limbo free\n     * snapshot version number.\n     */    withLastLimboFreeSnapshotVersion(e) {\n        return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken, this.expectedCount);\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Serializer for values stored in the LocalStore. */ class __PRIVATE_LocalSerializer {\n    constructor(e) {\n        this.ct = e;\n    }\n}\n\n/** Decodes a remote document from storage locally to a Document. */ function __PRIVATE_fromDbRemoteDocument(e, t) {\n    let n;\n    if (t.document) n = __PRIVATE_fromDocument(e.ct, t.document, !!t.hasCommittedMutations); else if (t.noDocument) {\n        const e = DocumentKey.fromSegments(t.noDocument.path), r = __PRIVATE_fromDbTimestamp(t.noDocument.readTime);\n        n = MutableDocument.newNoDocument(e, r), t.hasCommittedMutations && n.setHasCommittedMutations();\n    } else {\n        if (!t.unknownDocument) return fail();\n        {\n            const e = DocumentKey.fromSegments(t.unknownDocument.path), r = __PRIVATE_fromDbTimestamp(t.unknownDocument.version);\n            n = MutableDocument.newUnknownDocument(e, r);\n        }\n    }\n    return t.readTime && n.setReadTime(function __PRIVATE_fromDbTimestampKey(e) {\n        const t = new Timestamp(e[0], e[1]);\n        return SnapshotVersion.fromTimestamp(t);\n    }(t.readTime)), n;\n}\n\n/** Encodes a document for storage locally. */ function __PRIVATE_toDbRemoteDocument(e, t) {\n    const n = t.key, r = {\n        prefixPath: n.getCollectionPath().popLast().toArray(),\n        collectionGroup: n.collectionGroup,\n        documentId: n.path.lastSegment(),\n        readTime: __PRIVATE_toDbTimestampKey(t.readTime),\n        hasCommittedMutations: t.hasCommittedMutations\n    };\n    if (t.isFoundDocument()) r.document = function __PRIVATE_toDocument(e, t) {\n        return {\n            name: __PRIVATE_toName(e, t.key),\n            fields: t.data.value.mapValue.fields,\n            updateTime: toTimestamp(e, t.version.toTimestamp()),\n            createTime: toTimestamp(e, t.createTime.toTimestamp())\n        };\n    }(e.ct, t); else if (t.isNoDocument()) r.noDocument = {\n        path: n.path.toArray(),\n        readTime: __PRIVATE_toDbTimestamp(t.version)\n    }; else {\n        if (!t.isUnknownDocument()) return fail();\n        r.unknownDocument = {\n            path: n.path.toArray(),\n            version: __PRIVATE_toDbTimestamp(t.version)\n        };\n    }\n    return r;\n}\n\nfunction __PRIVATE_toDbTimestampKey(e) {\n    const t = e.toTimestamp();\n    return [ t.seconds, t.nanoseconds ];\n}\n\nfunction __PRIVATE_toDbTimestamp(e) {\n    const t = e.toTimestamp();\n    return {\n        seconds: t.seconds,\n        nanoseconds: t.nanoseconds\n    };\n}\n\nfunction __PRIVATE_fromDbTimestamp(e) {\n    const t = new Timestamp(e.seconds, e.nanoseconds);\n    return SnapshotVersion.fromTimestamp(t);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n/** Decodes a DbMutationBatch into a MutationBatch */\nfunction __PRIVATE_fromDbMutationBatch(e, t) {\n    const n = (t.baseMutations || []).map((t => __PRIVATE_fromMutation(e.ct, t)));\n    // Squash old transform mutations into existing patch or set mutations.\n    // The replacement of representing `transforms` with `update_transforms`\n    // on the SDK means that old `transform` mutations stored in IndexedDB need\n    // to be updated to `update_transforms`.\n    // TODO(b/174608374): Remove this code once we perform a schema migration.\n        for (let e = 0; e < t.mutations.length - 1; ++e) {\n        const n = t.mutations[e];\n        if (e + 1 < t.mutations.length && void 0 !== t.mutations[e + 1].transform) {\n            const r = t.mutations[e + 1];\n            n.updateTransforms = r.transform.fieldTransforms, t.mutations.splice(e + 1, 1), \n            ++e;\n        }\n    }\n    const r = t.mutations.map((t => __PRIVATE_fromMutation(e.ct, t))), i = Timestamp.fromMillis(t.localWriteTimeMs);\n    return new MutationBatch(t.batchId, i, n, r);\n}\n\n/** Decodes a DbTarget into TargetData */ function __PRIVATE_fromDbTarget(e) {\n    const t = __PRIVATE_fromDbTimestamp(e.readTime), n = void 0 !== e.lastLimboFreeSnapshotVersion ? __PRIVATE_fromDbTimestamp(e.lastLimboFreeSnapshotVersion) : SnapshotVersion.min();\n    let r;\n    return r = \n    /**\n * A helper function for figuring out what kind of query has been stored.\n */\n    function __PRIVATE_isDocumentQuery(e) {\n        return void 0 !== e.documents;\n    }\n    /** Encodes a DbBundle to a BundleMetadata object. */ (e.query) ? function __PRIVATE_fromDocumentsTarget(e) {\n        return __PRIVATE_hardAssert(1 === e.documents.length), __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e.documents[0])));\n    }(e.query) : function __PRIVATE_fromQueryTarget(e) {\n        return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e));\n    }(e.query), new TargetData(r, e.targetId, \"TargetPurposeListen\" /* TargetPurpose.Listen */ , e.lastListenSequenceNumber, t, n, ByteString.fromBase64String(e.resumeToken));\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */ function __PRIVATE_toDbTarget(e, t) {\n    const n = __PRIVATE_toDbTimestamp(t.snapshotVersion), r = __PRIVATE_toDbTimestamp(t.lastLimboFreeSnapshotVersion);\n    let i;\n    i = __PRIVATE_targetIsDocumentTarget(t.target) ? __PRIVATE_toDocumentsTarget(e.ct, t.target) : __PRIVATE_toQueryTarget(e.ct, t.target);\n    // We can't store the resumeToken as a ByteString in IndexedDb, so we\n    // convert it to a base64 string for storage.\n        const s = t.resumeToken.toBase64();\n    // lastListenSequenceNumber is always 0 until we do real GC.\n        return {\n        targetId: t.targetId,\n        canonicalId: __PRIVATE_canonifyTarget(t.target),\n        readTime: n,\n        resumeToken: s,\n        lastListenSequenceNumber: t.sequenceNumber,\n        lastLimboFreeSnapshotVersion: r,\n        query: i\n    };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nfunction __PRIVATE_fromBundledQuery(e) {\n    const t = __PRIVATE_convertQueryTargetToQuery({\n        parent: e.parent,\n        structuredQuery: e.structuredQuery\n    });\n    return \"LAST\" === e.limitType ? __PRIVATE_queryWithLimit(t, t.limit, \"L\" /* LimitType.Last */) : t;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nfunction __PRIVATE_fromDbDocumentOverlay(e, t) {\n    return new Overlay(t.largestBatchId, __PRIVATE_fromMutation(e.ct, t.overlayMutation));\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nfunction __PRIVATE_toDbDocumentOverlayKey(e, t) {\n    const n = t.path.lastSegment();\n    return [ e, __PRIVATE_encodeResourcePath(t.path.popLast()), n ];\n}\n\nfunction __PRIVATE_toDbIndexState(e, t, n, r) {\n    return {\n        indexId: e,\n        uid: t.uid || \"\",\n        sequenceNumber: n,\n        readTime: __PRIVATE_toDbTimestamp(r.readTime),\n        documentKey: __PRIVATE_encodeResourcePath(r.documentKey.path),\n        largestBatchId: r.largestBatchId\n    };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_IndexedDbBundleCache {\n    getBundleMetadata(e, t) {\n        return __PRIVATE_bundlesStore(e).get(t).next((e => {\n            if (e) return function __PRIVATE_fromDbBundle(e) {\n                return {\n                    id: e.bundleId,\n                    createTime: __PRIVATE_fromDbTimestamp(e.createTime),\n                    version: e.version\n                };\n            }\n            /** Encodes a BundleMetadata to a DbBundle. */ (e);\n        }));\n    }\n    saveBundleMetadata(e, t) {\n        return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e) {\n            return {\n                bundleId: e.id,\n                createTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.createTime)),\n                version: e.version\n            };\n        }\n        /** Encodes a DbNamedQuery to a NamedQuery. */ (t));\n    }\n    getNamedQuery(e, t) {\n        return __PRIVATE_namedQueriesStore(e).get(t).next((e => {\n            if (e) return function __PRIVATE_fromDbNamedQuery(e) {\n                return {\n                    name: e.name,\n                    query: __PRIVATE_fromBundledQuery(e.bundledQuery),\n                    readTime: __PRIVATE_fromDbTimestamp(e.readTime)\n                };\n            }\n            /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ (e);\n        }));\n    }\n    saveNamedQuery(e, t) {\n        return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e) {\n            return {\n                name: e.name,\n                readTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.readTime)),\n                bundledQuery: e.bundledQuery\n            };\n        }(t));\n    }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */ function __PRIVATE_bundlesStore(e) {\n    return __PRIVATE_getStore(e, \"bundles\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */ function __PRIVATE_namedQueriesStore(e) {\n    return __PRIVATE_getStore(e, \"namedQueries\");\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */ class __PRIVATE_IndexedDbDocumentOverlayCache {\n    /**\n     * @param serializer - The document serializer.\n     * @param userId - The userId for which we are accessing overlays.\n     */\n    constructor(e, t) {\n        this.serializer = e, this.userId = t;\n    }\n    static lt(e, t) {\n        const n = t.uid || \"\";\n        return new __PRIVATE_IndexedDbDocumentOverlayCache(e, n);\n    }\n    getOverlay(e, t) {\n        return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId, t)).next((e => e ? __PRIVATE_fromDbDocumentOverlay(this.serializer, e) : null));\n    }\n    getOverlays(e, t) {\n        const n = __PRIVATE_newOverlayMap();\n        return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => {\n            null !== e && n.set(t, e);\n        })))).next((() => n));\n    }\n    saveOverlays(e, t, n) {\n        const r = [];\n        return n.forEach(((n, i) => {\n            const s = new Overlay(t, i);\n            r.push(this.ht(e, s));\n        })), PersistencePromise.waitFor(r);\n    }\n    removeOverlaysForBatchId(e, t, n) {\n        const r = new Set;\n        // Get the set of unique collection paths.\n                t.forEach((e => r.add(__PRIVATE_encodeResourcePath(e.getCollectionPath()))));\n        const i = [];\n        return r.forEach((t => {\n            const r = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, n + 1 ], \n            /*lowerOpen=*/ !1, \n            /*upperOpen=*/ !0);\n            i.push(__PRIVATE_documentOverlayStore(e).J(\"collectionPathOverlayIndex\", r));\n        })), PersistencePromise.waitFor(i);\n    }\n    getOverlaysForCollection(e, t, n) {\n        const r = __PRIVATE_newOverlayMap(), i = __PRIVATE_encodeResourcePath(t), s = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], \n        /*lowerOpen=*/ !0);\n        return __PRIVATE_documentOverlayStore(e).G(\"collectionPathOverlayIndex\", s).next((e => {\n            for (const t of e) {\n                const e = __PRIVATE_fromDbDocumentOverlay(this.serializer, t);\n                r.set(e.getKey(), e);\n            }\n            return r;\n        }));\n    }\n    getOverlaysForCollectionGroup(e, t, n, r) {\n        const i = __PRIVATE_newOverlayMap();\n        let s;\n        // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n        // is not inclusive.\n                const o = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, Number.POSITIVE_INFINITY ], \n        /*lowerOpen=*/ !0);\n        return __PRIVATE_documentOverlayStore(e).Z({\n            index: \"collectionGroupOverlayIndex\",\n            range: o\n        }, ((e, t, n) => {\n            // We do not want to return partial batch overlays, even if the size\n            // of the result set exceeds the given `count` argument. Therefore, we\n            // continue to aggregate results even after the result size exceeds\n            // `count` if there are more overlays from the `currentBatchId`.\n            const o = __PRIVATE_fromDbDocumentOverlay(this.serializer, t);\n            i.size() < r || o.largestBatchId === s ? (i.set(o.getKey(), o), s = o.largestBatchId) : n.done();\n        })).next((() => i));\n    }\n    ht(e, t) {\n        return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e, t, n) {\n            const [r, i, s] = __PRIVATE_toDbDocumentOverlayKey(t, n.mutation.key);\n            return {\n                userId: t,\n                collectionPath: i,\n                documentId: s,\n                collectionGroup: n.mutation.key.getCollectionGroup(),\n                largestBatchId: n.largestBatchId,\n                overlayMutation: toMutation(e.ct, n.mutation)\n            };\n        }(this.serializer, this.userId, t));\n    }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */ function __PRIVATE_documentOverlayStore(e) {\n    return __PRIVATE_getStore(e, \"documentOverlays\");\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n/** Firestore index value writer.  */\nclass __PRIVATE_FirestoreIndexValueWriter {\n    constructor() {}\n    // The write methods below short-circuit writing terminators for values\n    // containing a (terminating) truncated value.\n    // As an example, consider the resulting encoding for:\n    // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n    // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n    // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n    /** Writes an index value.  */\n    Pt(e, t) {\n        this.It(e, t), \n        // Write separator to split index values\n        // (see go/firestore-storage-format#encodings).\n        t.Tt();\n    }\n    It(e, t) {\n        if (\"nullValue\" in e) this.Et(t, 5); else if (\"booleanValue\" in e) this.Et(t, 10), \n        t.dt(e.booleanValue ? 1 : 0); else if (\"integerValue\" in e) this.Et(t, 15), t.dt(__PRIVATE_normalizeNumber(e.integerValue)); else if (\"doubleValue\" in e) {\n            const n = __PRIVATE_normalizeNumber(e.doubleValue);\n            isNaN(n) ? this.Et(t, 13) : (this.Et(t, 15), __PRIVATE_isNegativeZero(n) ? \n            // -0.0, 0 and 0.0 are all considered the same\n            t.dt(0) : t.dt(n));\n        } else if (\"timestampValue\" in e) {\n            const n = e.timestampValue;\n            this.Et(t, 20), \"string\" == typeof n ? t.At(n) : (t.At(`${n.seconds || \"\"}`), t.dt(n.nanos || 0));\n        } else if (\"stringValue\" in e) this.Rt(e.stringValue, t), this.Vt(t); else if (\"bytesValue\" in e) this.Et(t, 30), \n        t.ft(__PRIVATE_normalizeByteString(e.bytesValue)), this.Vt(t); else if (\"referenceValue\" in e) this.gt(e.referenceValue, t); else if (\"geoPointValue\" in e) {\n            const n = e.geoPointValue;\n            this.Et(t, 45), t.dt(n.latitude || 0), t.dt(n.longitude || 0);\n        } else \"mapValue\" in e ? __PRIVATE_isMaxValue(e) ? this.Et(t, Number.MAX_SAFE_INTEGER) : (this.yt(e.mapValue, t), \n        this.Vt(t)) : \"arrayValue\" in e ? (this.wt(e.arrayValue, t), this.Vt(t)) : fail();\n    }\n    Rt(e, t) {\n        this.Et(t, 25), this.St(e, t);\n    }\n    St(e, t) {\n        t.At(e);\n    }\n    yt(e, t) {\n        const n = e.fields || {};\n        this.Et(t, 55);\n        for (const e of Object.keys(n)) this.Rt(e, t), this.It(n[e], t);\n    }\n    wt(e, t) {\n        const n = e.values || [];\n        this.Et(t, 50);\n        for (const e of n) this.It(e, t);\n    }\n    gt(e, t) {\n        this.Et(t, 37);\n        DocumentKey.fromName(e).path.forEach((e => {\n            this.Et(t, 60), this.St(e, t);\n        }));\n    }\n    Et(e, t) {\n        e.dt(t);\n    }\n    Vt(e) {\n        // While the SDK does not implement truncation, the truncation marker is\n        // used to terminate all variable length values (which are strings, bytes,\n        // references, arrays and maps).\n        e.dt(2);\n    }\n}\n\n__PRIVATE_FirestoreIndexValueWriter.bt = new __PRIVATE_FirestoreIndexValueWriter;\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nfunction __PRIVATE_numberOfLeadingZerosInByte(e) {\n    if (0 === e) return 8;\n    let t = 0;\n    return e >> 4 == 0 && (\n    // Test if the first four bits are zero.\n    t += 4, e <<= 4), e >> 6 == 0 && (\n    // Test if the first two (or next two) bits are zero.\n    t += 2, e <<= 2), e >> 7 == 0 && (\n    // Test if the remaining bit is zero.\n    t += 1), t;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction __PRIVATE_unsignedNumLength(e) {\n    // This is just the number of bytes for the unsigned representation of the number.\n    const t = 64 - function __PRIVATE_numberOfLeadingZeros(e) {\n        let t = 0;\n        for (let n = 0; n < 8; ++n) {\n            const r = __PRIVATE_numberOfLeadingZerosInByte(255 & e[n]);\n            if (t += r, 8 !== r) break;\n        }\n        return t;\n    }(e);\n    return Math.ceil(t / 8);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */ class __PRIVATE_OrderedCodeWriter {\n    constructor() {\n        this.buffer = new Uint8Array(1024), this.position = 0;\n    }\n    Dt(e) {\n        const t = e[Symbol.iterator]();\n        let n = t.next();\n        for (;!n.done; ) this.vt(n.value), n = t.next();\n        this.Ct();\n    }\n    Ft(e) {\n        const t = e[Symbol.iterator]();\n        let n = t.next();\n        for (;!n.done; ) this.Mt(n.value), n = t.next();\n        this.xt();\n    }\n    /** Writes utf8 bytes into this byte sequence, ascending. */    Ot(e) {\n        for (const t of e) {\n            const e = t.charCodeAt(0);\n            if (e < 128) this.vt(e); else if (e < 2048) this.vt(960 | e >>> 6), this.vt(128 | 63 & e); else if (t < \"\\ud800\" || \"\\udbff\" < t) this.vt(480 | e >>> 12), \n            this.vt(128 | 63 & e >>> 6), this.vt(128 | 63 & e); else {\n                const e = t.codePointAt(0);\n                this.vt(240 | e >>> 18), this.vt(128 | 63 & e >>> 12), this.vt(128 | 63 & e >>> 6), \n                this.vt(128 | 63 & e);\n            }\n        }\n        this.Ct();\n    }\n    /** Writes utf8 bytes into this byte sequence, descending */    Nt(e) {\n        for (const t of e) {\n            const e = t.charCodeAt(0);\n            if (e < 128) this.Mt(e); else if (e < 2048) this.Mt(960 | e >>> 6), this.Mt(128 | 63 & e); else if (t < \"\\ud800\" || \"\\udbff\" < t) this.Mt(480 | e >>> 12), \n            this.Mt(128 | 63 & e >>> 6), this.Mt(128 | 63 & e); else {\n                const e = t.codePointAt(0);\n                this.Mt(240 | e >>> 18), this.Mt(128 | 63 & e >>> 12), this.Mt(128 | 63 & e >>> 6), \n                this.Mt(128 | 63 & e);\n            }\n        }\n        this.xt();\n    }\n    Bt(e) {\n        // Values are encoded with a single byte length prefix, followed by the\n        // actual value in big-endian format with leading 0 bytes dropped.\n        const t = this.Lt(e), n = __PRIVATE_unsignedNumLength(t);\n        this.kt(1 + n), this.buffer[this.position++] = 255 & n;\n        // Write the length\n        for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = 255 & t[e];\n    }\n    qt(e) {\n        // Values are encoded with a single byte length prefix, followed by the\n        // inverted value in big-endian format with leading 0 bytes dropped.\n        const t = this.Lt(e), n = __PRIVATE_unsignedNumLength(t);\n        this.kt(1 + n), this.buffer[this.position++] = ~(255 & n);\n        // Write the length\n        for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = ~(255 & t[e]);\n    }\n    /**\n     * Writes the \"infinity\" byte sequence that sorts after all other byte\n     * sequences written in ascending order.\n     */    Qt() {\n        this.Kt(255), this.Kt(255);\n    }\n    /**\n     * Writes the \"infinity\" byte sequence that sorts before all other byte\n     * sequences written in descending order.\n     */    $t() {\n        this.Ut(255), this.Ut(255);\n    }\n    /**\n     * Resets the buffer such that it is the same as when it was newly\n     * constructed.\n     */    reset() {\n        this.position = 0;\n    }\n    seed(e) {\n        this.kt(e.length), this.buffer.set(e, this.position), this.position += e.length;\n    }\n    /** Makes a copy of the encoded bytes in this buffer.  */    Wt() {\n        return this.buffer.slice(0, this.position);\n    }\n    /**\n     * Encodes `val` into an encoding so that the order matches the IEEE 754\n     * floating-point comparison results with the following exceptions:\n     *   -0.0 < 0.0\n     *   all non-NaN < NaN\n     *   NaN = NaN\n     */    Lt(e) {\n        const t = \n        /** Converts a JavaScript number to a byte array (using big endian encoding). */\n        function __PRIVATE_doubleToLongBits(e) {\n            const t = new DataView(new ArrayBuffer(8));\n            return t.setFloat64(0, e, /* littleEndian= */ !1), new Uint8Array(t.buffer);\n        }(e), n = 0 != (128 & t[0]);\n        // Check if the first bit is set. We use a bit mask since value[0] is\n        // encoded as a number from 0 to 255.\n                // Revert the two complement to get natural ordering\n        t[0] ^= n ? 255 : 128;\n        for (let e = 1; e < t.length; ++e) t[e] ^= n ? 255 : 0;\n        return t;\n    }\n    /** Writes a single byte ascending to the buffer. */    vt(e) {\n        const t = 255 & e;\n        0 === t ? (this.Kt(0), this.Kt(255)) : 255 === t ? (this.Kt(255), this.Kt(0)) : this.Kt(t);\n    }\n    /** Writes a single byte descending to the buffer.  */    Mt(e) {\n        const t = 255 & e;\n        0 === t ? (this.Ut(0), this.Ut(255)) : 255 === t ? (this.Ut(255), this.Ut(0)) : this.Ut(e);\n    }\n    Ct() {\n        this.Kt(0), this.Kt(1);\n    }\n    xt() {\n        this.Ut(0), this.Ut(1);\n    }\n    Kt(e) {\n        this.kt(1), this.buffer[this.position++] = e;\n    }\n    Ut(e) {\n        this.kt(1), this.buffer[this.position++] = ~e;\n    }\n    kt(e) {\n        const t = e + this.position;\n        if (t <= this.buffer.length) return;\n        // Try doubling.\n                let n = 2 * this.buffer.length;\n        // Still not big enough? Just allocate the right size.\n                n < t && (n = t);\n        // Create the new buffer.\n                const r = new Uint8Array(n);\n        r.set(this.buffer), // copy old data\n        this.buffer = r;\n    }\n}\n\nclass __PRIVATE_AscendingIndexByteEncoder {\n    constructor(e) {\n        this.Gt = e;\n    }\n    ft(e) {\n        this.Gt.Dt(e);\n    }\n    At(e) {\n        this.Gt.Ot(e);\n    }\n    dt(e) {\n        this.Gt.Bt(e);\n    }\n    Tt() {\n        this.Gt.Qt();\n    }\n}\n\nclass __PRIVATE_DescendingIndexByteEncoder {\n    constructor(e) {\n        this.Gt = e;\n    }\n    ft(e) {\n        this.Gt.Ft(e);\n    }\n    At(e) {\n        this.Gt.Nt(e);\n    }\n    dt(e) {\n        this.Gt.qt(e);\n    }\n    Tt() {\n        this.Gt.$t();\n    }\n}\n\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */ class __PRIVATE_IndexByteEncoder {\n    constructor() {\n        this.Gt = new __PRIVATE_OrderedCodeWriter, this.zt = new __PRIVATE_AscendingIndexByteEncoder(this.Gt), \n        this.jt = new __PRIVATE_DescendingIndexByteEncoder(this.Gt);\n    }\n    seed(e) {\n        this.Gt.seed(e);\n    }\n    Ht(e) {\n        return 0 /* IndexKind.ASCENDING */ === e ? this.zt : this.jt;\n    }\n    Wt() {\n        return this.Gt.Wt();\n    }\n    reset() {\n        this.Gt.reset();\n    }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Represents an index entry saved by the SDK in persisted storage. */ class __PRIVATE_IndexEntry {\n    constructor(e, t, n, r) {\n        this.indexId = e, this.documentKey = t, this.arrayValue = n, this.directionalValue = r;\n    }\n    /**\n     * Returns an IndexEntry entry that sorts immediately after the current\n     * directional value.\n     */    Jt() {\n        const e = this.directionalValue.length, t = 0 === e || 255 === this.directionalValue[e - 1] ? e + 1 : e, n = new Uint8Array(t);\n        return n.set(this.directionalValue, 0), t !== e ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1], \n        new __PRIVATE_IndexEntry(this.indexId, this.documentKey, this.arrayValue, n);\n    }\n}\n\nfunction __PRIVATE_indexEntryComparator(e, t) {\n    let n = e.indexId - t.indexId;\n    return 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.arrayValue, t.arrayValue), \n    0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.directionalValue, t.directionalValue), \n    0 !== n ? n : DocumentKey.comparator(e.documentKey, t.documentKey)));\n}\n\nfunction __PRIVATE_compareByteArrays(e, t) {\n    for (let n = 0; n < e.length && n < t.length; ++n) {\n        const r = e[n] - t[n];\n        if (0 !== r) return r;\n    }\n    return e.length - t.length;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query                                               | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b')         | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b')         | a ASC\n * where('a', '==', 'a').where('b', '==', 'b')         | b DESC\n * where('a', '>=', 'a').orderBy('a')                  | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc')          | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b')     | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b')     | a ASC\n * where('a', 'array-contains', 'a').orderBy('b')      | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b')      | a CONTAINS\n */ class __PRIVATE_TargetIndexMatcher {\n    constructor(e) {\n        this.collectionId = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment(), \n        this.Yt = e.orderBy, this.Zt = [];\n        for (const t of e.filters) {\n            const e = t;\n            e.isInequality() ? this.Xt = e : this.Zt.push(e);\n        }\n    }\n    /**\n     * Returns whether the index can be used to serve the TargetIndexMatcher's\n     * target.\n     *\n     * An index is considered capable of serving the target when:\n     * - The target uses all index segments for its filters and orderBy clauses.\n     *   The target can have additional filter and orderBy clauses, but not\n     *   fewer.\n     * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n     *   have a corresponding `CONTAINS` segment.\n     * - All directional index segments can be mapped to the target as a series of\n     *   equality filters, a single inequality filter and a series of orderBy\n     *   clauses.\n     * - The segments that represent the equality filters may appear out of order.\n     * - The optional segment for the inequality filter must appear after all\n     *   equality segments.\n     * - The segments that represent that orderBy clause of the target must appear\n     *   in order after all equality and inequality segments. Single orderBy\n     *   clauses cannot be skipped, but a continuous orderBy suffix may be\n     *   omitted.\n     */    en(e) {\n        __PRIVATE_hardAssert(e.collectionGroup === this.collectionId);\n        // If there is an array element, find a matching filter.\n        const t = __PRIVATE_fieldIndexGetArraySegment(e);\n        if (void 0 !== t && !this.tn(t)) return !1;\n        const n = __PRIVATE_fieldIndexGetDirectionalSegments(e);\n        let r = new Set, i = 0, s = 0;\n        // Process all equalities first. Equalities can appear out of order.\n        for (;i < n.length && this.tn(n[i]); ++i) r = r.add(n[i].fieldPath.canonicalString());\n        // If we already have processed all segments, all segments are used to serve\n        // the equality filters and we do not need to map any segments to the\n        // target's inequality and orderBy clauses.\n                if (i === n.length) return !0;\n        if (void 0 !== this.Xt) {\n            // If there is an inequality filter and the field was not in one of the\n            // equality filters above, the next segment must match both the filter\n            // and the first orderBy clause.\n            if (!r.has(this.Xt.field.canonicalString())) {\n                const e = n[i];\n                if (!this.nn(this.Xt, e) || !this.rn(this.Yt[s++], e)) return !1;\n            }\n            ++i;\n        }\n        // All remaining segments need to represent the prefix of the target's\n        // orderBy.\n                for (;i < n.length; ++i) {\n            const e = n[i];\n            if (s >= this.Yt.length || !this.rn(this.Yt[s++], e)) return !1;\n        }\n        return !0;\n    }\n    tn(e) {\n        for (const t of this.Zt) if (this.nn(t, e)) return !0;\n        return !1;\n    }\n    nn(e, t) {\n        if (void 0 === e || !e.field.isEqual(t.fieldPath)) return !1;\n        const n = \"array-contains\" /* Operator.ARRAY_CONTAINS */ === e.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === e.op;\n        return 2 /* IndexKind.CONTAINS */ === t.kind === n;\n    }\n    rn(e, t) {\n        return !!e.field.isEqual(t.fieldPath) && (0 /* IndexKind.ASCENDING */ === t.kind && \"asc\" /* Direction.ASCENDING */ === e.dir || 1 /* IndexKind.DESCENDING */ === t.kind && \"desc\" /* Direction.DESCENDING */ === e.dir);\n    }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */ function __PRIVATE_computeInExpansion(e) {\n    var t, n;\n    if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n    e instanceof FieldFilter) {\n        if (e instanceof __PRIVATE_InFilter) {\n            const r = (null === (n = null === (t = e.value.arrayValue) || void 0 === t ? void 0 : t.values) || void 0 === n ? void 0 : n.map((t => FieldFilter.create(e.field, \"==\" /* Operator.EQUAL */ , t)))) || [];\n            return CompositeFilter.create(r, \"or\" /* CompositeOperator.OR */);\n        }\n        // We have reached other kinds of field filters.\n        return e;\n    }\n    // We have a composite filter.\n        const r = e.filters.map((e => __PRIVATE_computeInExpansion(e)));\n    return CompositeFilter.create(r, e.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n * <p>Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */ function __PRIVATE_getDnfTerms(e) {\n    if (0 === e.getFilters().length) return [];\n    const t = __PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e));\n    return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(t)), __PRIVATE_isSingleFieldFilter(t) || __PRIVATE_isFlatConjunction(t) ? [ t ] : t.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function __PRIVATE_isSingleFieldFilter(e) {\n    return e instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */ function __PRIVATE_isFlatConjunction(e) {\n    return e instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(e);\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */ function __PRIVATE_isDisjunctiveNormalForm(e) {\n    return __PRIVATE_isSingleFieldFilter(e) || __PRIVATE_isFlatConjunction(e) || \n    /**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\n    function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e) {\n        if (e instanceof CompositeFilter && __PRIVATE_compositeFilterIsDisjunction(e)) {\n            for (const t of e.getFilters()) if (!__PRIVATE_isSingleFieldFilter(t) && !__PRIVATE_isFlatConjunction(t)) return !1;\n            return !0;\n        }\n        return !1;\n    }(e);\n}\n\nfunction __PRIVATE_computeDistributedNormalForm(e) {\n    if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n    e instanceof FieldFilter) return e;\n    if (1 === e.filters.length) return __PRIVATE_computeDistributedNormalForm(e.filters[0]);\n    // Compute DNF for each of the subfilters first\n        const t = e.filters.map((e => __PRIVATE_computeDistributedNormalForm(e)));\n    let n = CompositeFilter.create(t, e.op);\n    return n = __PRIVATE_applyAssociation(n), __PRIVATE_isDisjunctiveNormalForm(n) ? n : (__PRIVATE_hardAssert(n instanceof CompositeFilter), \n    __PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(n)), __PRIVATE_hardAssert(n.filters.length > 1), \n    n.filters.reduce(((e, t) => __PRIVATE_applyDistribution(e, t))));\n}\n\nfunction __PRIVATE_applyDistribution(e, t) {\n    let n;\n    return __PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n    __PRIVATE_hardAssert(t instanceof FieldFilter || t instanceof CompositeFilter), \n    // FieldFilter FieldFilter\n    n = e instanceof FieldFilter ? t instanceof FieldFilter ? function __PRIVATE_applyDistributionFieldFilters(e, t) {\n        // Conjunction distribution for two field filters is the conjunction of them.\n        return CompositeFilter.create([ e, t ], \"and\" /* CompositeOperator.AND */);\n    }(e, t) : __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) : t instanceof FieldFilter ? __PRIVATE_applyDistributionFieldAndCompositeFilters(t, e) : function __PRIVATE_applyDistributionCompositeFilters(e, t) {\n        // There are four cases:\n        // (A & B) & (C & D) --> (A & B & C & D)\n        // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n        // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n        // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n        // Case 1 is a merge.\n        if (__PRIVATE_hardAssert(e.filters.length > 0 && t.filters.length > 0), __PRIVATE_compositeFilterIsConjunction(e) && __PRIVATE_compositeFilterIsConjunction(t)) return __PRIVATE_compositeFilterWithAddedFilters(e, t.getFilters());\n        // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n        // we should take each element of the disjunction and distribute it over the other side, and\n        // return the disjunction of the distribution results.\n                const n = __PRIVATE_compositeFilterIsDisjunction(e) ? e : t, r = __PRIVATE_compositeFilterIsDisjunction(e) ? t : e, i = n.filters.map((e => __PRIVATE_applyDistribution(e, r)));\n        return CompositeFilter.create(i, \"or\" /* CompositeOperator.OR */);\n    }(e, t), __PRIVATE_applyAssociation(n);\n}\n\nfunction __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) {\n    // There are two cases:\n    // A & (B & C) --> (A & B & C)\n    // A & (B | C) --> (A & B) | (A & C)\n    if (__PRIVATE_compositeFilterIsConjunction(t)) \n    // Case 1\n    return __PRIVATE_compositeFilterWithAddedFilters(t, e.getFilters());\n    {\n        // Case 2\n        const n = t.filters.map((t => __PRIVATE_applyDistribution(e, t)));\n        return CompositeFilter.create(n, \"or\" /* CompositeOperator.OR */);\n    }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n * <ul>\n *   <li>A | (B | C) == (A | B) | C == (A | B | C)\n *   <li>A & (B & C) == (A & B) & C == (A & B & C)\n * </ul>\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */ function __PRIVATE_applyAssociation(e) {\n    if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter), \n    e instanceof FieldFilter) return e;\n    const t = e.getFilters();\n    // If the composite filter only contains 1 filter, apply associativity to it.\n        if (1 === t.length) return __PRIVATE_applyAssociation(t[0]);\n    // Associativity applied to a flat composite filter results is itself.\n        if (__PRIVATE_compositeFilterIsFlat(e)) return e;\n    // First apply associativity to all subfilters. This will in turn recursively apply\n    // associativity to all nested composite filters and field filters.\n        const n = t.map((e => __PRIVATE_applyAssociation(e))), r = [];\n    // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n    // take out their filters and add them to `compositeFilter`. For example:\n    // compositeFilter = (A | (B | C | D))\n    // compositeSubfilter = (B | C | D)\n    // Result: (A | B | C | D)\n    // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n    // added to the top-level \"compositeFilter\".\n        return n.forEach((t => {\n        t instanceof FieldFilter ? r.push(t) : t instanceof CompositeFilter && (t.op === e.op ? \n        // compositeFilter: (A | (B | C))\n        // compositeSubfilter: (B | C)\n        // Result: (A | B | C)\n        r.push(...t.filters) : \n        // compositeFilter: (A | (B & C))\n        // compositeSubfilter: (B & C)\n        // Result: (A | (B & C))\n        r.push(t));\n    })), 1 === r.length ? r[0] : CompositeFilter.create(r, e.op);\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of IndexManager.\n */ class __PRIVATE_MemoryIndexManager {\n    constructor() {\n        this.sn = new __PRIVATE_MemoryCollectionParentIndex;\n    }\n    addToCollectionParentIndex(e, t) {\n        return this.sn.add(t), PersistencePromise.resolve();\n    }\n    getCollectionParents(e, t) {\n        return PersistencePromise.resolve(this.sn.getEntries(t));\n    }\n    addFieldIndex(e, t) {\n        // Field indices are not supported with memory persistence.\n        return PersistencePromise.resolve();\n    }\n    deleteFieldIndex(e, t) {\n        // Field indices are not supported with memory persistence.\n        return PersistencePromise.resolve();\n    }\n    getDocumentsMatchingTarget(e, t) {\n        // Field indices are not supported with memory persistence.\n        return PersistencePromise.resolve(null);\n    }\n    getIndexType(e, t) {\n        // Field indices are not supported with memory persistence.\n        return PersistencePromise.resolve(0 /* IndexType.NONE */);\n    }\n    getFieldIndexes(e, t) {\n        // Field indices are not supported with memory persistence.\n        return PersistencePromise.resolve([]);\n    }\n    getNextCollectionGroupToUpdate(e) {\n        // Field indices are not supported with memory persistence.\n        return PersistencePromise.resolve(null);\n    }\n    getMinOffset(e, t) {\n        return PersistencePromise.resolve(IndexOffset.min());\n    }\n    getMinOffsetFromCollectionGroup(e, t) {\n        return PersistencePromise.resolve(IndexOffset.min());\n    }\n    updateCollectionGroup(e, t, n) {\n        // Field indices are not supported with memory persistence.\n        return PersistencePromise.resolve();\n    }\n    updateIndexEntries(e, t) {\n        // Field indices are not supported with memory persistence.\n        return PersistencePromise.resolve();\n    }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */ class __PRIVATE_MemoryCollectionParentIndex {\n    constructor() {\n        this.index = {};\n    }\n    // Returns false if the entry already existed.\n    add(e) {\n        const t = e.lastSegment(), n = e.popLast(), r = this.index[t] || new SortedSet(ResourcePath.comparator), i = !r.has(n);\n        return this.index[t] = r.add(n), i;\n    }\n    has(e) {\n        const t = e.lastSegment(), n = e.popLast(), r = this.index[t];\n        return r && r.has(n);\n    }\n    getEntries(e) {\n        return (this.index[e] || new SortedSet(ResourcePath.comparator)).toArray();\n    }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ee = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nclass __PRIVATE_IndexedDbIndexManager {\n    constructor(e, t) {\n        this.user = e, this.databaseId = t, \n        /**\n         * An in-memory copy of the index entries we've already written since the SDK\n         * launched. Used to avoid re-writing the same entry repeatedly.\n         *\n         * This is *NOT* a complete cache of what's in persistence and so can never be\n         * used to satisfy reads.\n         */\n        this.on = new __PRIVATE_MemoryCollectionParentIndex, \n        /**\n         * Maps from a target to its equivalent list of sub-targets. Each sub-target\n         * contains only one term from the target's disjunctive normal form (DNF).\n         */\n        this._n = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), ((e, t) => __PRIVATE_targetEquals(e, t))), \n        this.uid = e.uid || \"\";\n    }\n    /**\n     * Adds a new entry to the collection parent index.\n     *\n     * Repeated calls for the same collectionPath should be avoided within a\n     * transaction as IndexedDbIndexManager only caches writes once a transaction\n     * has been committed.\n     */    addToCollectionParentIndex(e, t) {\n        if (!this.on.has(t)) {\n            const n = t.lastSegment(), r = t.popLast();\n            e.addOnCommittedListener((() => {\n                // Add the collection to the in memory cache only if the transaction was\n                // successfully committed.\n                this.on.add(t);\n            }));\n            const i = {\n                collectionId: n,\n                parent: __PRIVATE_encodeResourcePath(r)\n            };\n            return __PRIVATE_collectionParentsStore(e).put(i);\n        }\n        return PersistencePromise.resolve();\n    }\n    getCollectionParents(e, t) {\n        const n = [], r = IDBKeyRange.bound([ t, \"\" ], [ __PRIVATE_immediateSuccessor(t), \"\" ], \n        /*lowerOpen=*/ !1, \n        /*upperOpen=*/ !0);\n        return __PRIVATE_collectionParentsStore(e).G(r).next((e => {\n            for (const r of e) {\n                // This collectionId guard shouldn't be necessary (and isn't as long\n                // as we're running in a real browser), but there's a bug in\n                // indexeddbshim that breaks our range in our tests running in node:\n                // https://github.com/axemclion/IndexedDBShim/issues/334\n                if (r.collectionId !== t) break;\n                n.push(__PRIVATE_decodeResourcePath(r.parent));\n            }\n            return n;\n        }));\n    }\n    addFieldIndex(e, t) {\n        // TODO(indexing): Verify that the auto-incrementing index ID works in\n        // Safari & Firefox.\n        const n = __PRIVATE_indexConfigurationStore(e), r = function __PRIVATE_toDbIndexConfiguration(e) {\n            return {\n                indexId: e.indexId,\n                collectionGroup: e.collectionGroup,\n                fields: e.fields.map((e => [ e.fieldPath.canonicalString(), e.kind ]))\n            };\n        }(t);\n        delete r.indexId;\n        // `indexId` is auto-populated by IndexedDb\n        const i = n.add(r);\n        if (t.indexState) {\n            const n = __PRIVATE_indexStateStore(e);\n            return i.next((e => {\n                n.put(__PRIVATE_toDbIndexState(e, this.user, t.indexState.sequenceNumber, t.indexState.offset));\n            }));\n        }\n        return i.next();\n    }\n    deleteFieldIndex(e, t) {\n        const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e), i = __PRIVATE_indexEntriesStore(e);\n        return n.delete(t.indexId).next((() => r.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], \n        /*lowerOpen=*/ !1, \n        /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], \n        /*lowerOpen=*/ !1, \n        /*upperOpen=*/ !0))));\n    }\n    getDocumentsMatchingTarget(e, t) {\n        const n = __PRIVATE_indexEntriesStore(e);\n        let r = !0;\n        const i = new Map;\n        return PersistencePromise.forEach(this.an(t), (t => this.un(e, t).next((e => {\n            r && (r = !!e), i.set(t, e);\n        })))).next((() => {\n            if (r) {\n                let e = __PRIVATE_documentKeySet();\n                const r = [];\n                return PersistencePromise.forEach(i, ((i, s) => {\n                    __PRIVATE_logDebug(\"IndexedDbIndexManager\", `Using index ${function __PRIVATE_fieldIndexToString(e) {\n                        return `id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e => `${e.fieldPath}:${e.kind}`)).join(\",\")}`;\n                    }(i)} to execute ${__PRIVATE_canonifyTarget(t)}`);\n                    const o = function __PRIVATE_targetGetArrayValues(e, t) {\n                        const n = __PRIVATE_fieldIndexGetArraySegment(t);\n                        if (void 0 === n) return null;\n                        for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, n.fieldPath)) switch (t.op) {\n                          case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n                            return t.value.arrayValue.values || [];\n\n                          case \"array-contains\" /* Operator.ARRAY_CONTAINS */ :\n                            return [ t.value ];\n                            // Remaining filters are not array filters.\n                                                }\n                        return null;\n                    }\n                    /**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */ (s, i), _ = function __PRIVATE_targetGetNotInValues(e, t) {\n                        const n = new Map;\n                        for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(t)) for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, r.fieldPath)) switch (t.op) {\n                          case \"==\" /* Operator.EQUAL */ :\n                          case \"in\" /* Operator.IN */ :\n                            // Encode equality prefix, which is encoded in the index value before\n                            // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n                            // `value != 'ab'`).\n                            n.set(r.fieldPath.canonicalString(), t.value);\n                            break;\n\n                          case \"not-in\" /* Operator.NOT_IN */ :\n                          case \"!=\" /* Operator.NOT_EQUAL */ :\n                            // NotIn/NotEqual is always a suffix. There cannot be any remaining\n                            // segments and hence we can return early here.\n                            return n.set(r.fieldPath.canonicalString(), t.value), Array.from(n.values());\n                            // Remaining filters cannot be used as notIn bounds.\n                                                }\n                        return null;\n                    }\n                    /**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */ (s, i), a = function __PRIVATE_targetGetLowerBound(e, t) {\n                        const n = [];\n                        let r = !0;\n                        // For each segment, retrieve a lower bound if there is a suitable filter or\n                        // startAt.\n                                                for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) {\n                            const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.startAt) : __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.startAt);\n                            n.push(t.value), r && (r = t.inclusive);\n                        }\n                        return new Bound(n, r);\n                    }\n                    /**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */ (s, i), u = function __PRIVATE_targetGetUpperBound(e, t) {\n                        const n = [];\n                        let r = !0;\n                        // For each segment, retrieve an upper bound if there is a suitable filter or\n                        // endAt.\n                                                for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) {\n                            const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.endAt) : __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.endAt);\n                            n.push(t.value), r && (r = t.inclusive);\n                        }\n                        return new Bound(n, r);\n                    }(s, i), c = this.cn(i, s, a), l = this.cn(i, s, u), h = this.ln(i, s, _), P = this.hn(i.indexId, o, c, a.inclusive, l, u.inclusive, h);\n                    return PersistencePromise.forEach(P, (i => n.H(i, t.limit).next((t => {\n                        t.forEach((t => {\n                            const n = DocumentKey.fromSegments(t.documentKey);\n                            e.has(n) || (e = e.add(n), r.push(n));\n                        }));\n                    }))));\n                })).next((() => r));\n            }\n            return PersistencePromise.resolve(null);\n        }));\n    }\n    an(e) {\n        let t = this._n.get(e);\n        if (t) return t;\n        if (0 === e.filters.length) t = [ e ]; else {\n            t = __PRIVATE_getDnfTerms(CompositeFilter.create(e.filters, \"and\" /* CompositeOperator.AND */)).map((t => __PRIVATE_newTarget(e.path, e.collectionGroup, e.orderBy, t.getFilters(), e.limit, e.startAt, e.endAt)));\n        }\n        return this._n.set(e, t), t;\n    }\n    /**\n     * Constructs a key range query on `DbIndexEntryStore` that unions all\n     * bounds.\n     */    hn(e, t, n, r, i, s, o) {\n        // The number of total index scans we union together. This is similar to a\n        // distributed normal form, but adapted for array values. We create a single\n        // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n        // combined with the values from the query bounds.\n        const _ = (null != t ? t.length : 1) * Math.max(n.length, i.length), a = _ / (null != t ? t.length : 1), u = [];\n        for (let c = 0; c < _; ++c) {\n            const _ = t ? this.Pn(t[c / a]) : Ee, l = this.In(e, _, n[c % a], r), h = this.Tn(e, _, i[c % a], s), P = o.map((t => this.In(e, _, t, \n            /* inclusive= */ !0)));\n            u.push(...this.createRange(l, h, P));\n        }\n        return u;\n    }\n    /** Generates the lower bound for `arrayValue` and `directionalValue`. */    In(e, t, n, r) {\n        const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);\n        return r ? i : i.Jt();\n    }\n    /** Generates the upper bound for `arrayValue` and `directionalValue`. */    Tn(e, t, n, r) {\n        const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);\n        return r ? i.Jt() : i;\n    }\n    un(e, t) {\n        const n = new __PRIVATE_TargetIndexMatcher(t), r = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment();\n        return this.getFieldIndexes(e, r).next((e => {\n            // Return the index with the most number of segments.\n            let t = null;\n            for (const r of e) {\n                n.en(r) && (!t || r.fields.length > t.fields.length) && (t = r);\n            }\n            return t;\n        }));\n    }\n    getIndexType(e, t) {\n        let n = 2 /* IndexType.FULL */;\n        const r = this.an(t);\n        return PersistencePromise.forEach(r, (t => this.un(e, t).next((e => {\n            e ? 0 /* IndexType.NONE */ !== n && e.fields.length < function __PRIVATE_targetGetSegmentCount(e) {\n                let t = new SortedSet(FieldPath$1.comparator), n = !1;\n                for (const r of e.filters) for (const e of r.getFlattenedFilters()) \n                // __name__ is not an explicit segment of any index, so we don't need to\n                // count it.\n                e.field.isKeyField() || (\n                // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n                // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n                // though these are on the same field, they should be counted as two\n                // separate segments in an index.\n                \"array-contains\" /* Operator.ARRAY_CONTAINS */ === e.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === e.op ? n = !0 : t = t.add(e.field));\n                for (const n of e.orderBy) \n                // __name__ is not an explicit segment of any index, so we don't need to\n                // count it.\n                n.field.isKeyField() || (t = t.add(n.field));\n                return t.size + (n ? 1 : 0);\n            }(t) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;\n        })))).next((() => \n        // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n        // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n        // and apply the limit in memory as a post-processing step.\n        function __PRIVATE_targetHasLimit(e) {\n            return null !== e.limit;\n        }(t) && r.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));\n    }\n    /**\n     * Returns the byte encoded form of the directional values in the field index.\n     * Returns `null` if the document does not have all fields specified in the\n     * index.\n     */    En(e, t) {\n        const n = new __PRIVATE_IndexByteEncoder;\n        for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {\n            const e = t.data.field(r.fieldPath);\n            if (null == e) return null;\n            const i = n.Ht(r.kind);\n            __PRIVATE_FirestoreIndexValueWriter.bt.Pt(e, i);\n        }\n        return n.Wt();\n    }\n    /** Encodes a single value to the ascending index format. */    Pn(e) {\n        const t = new __PRIVATE_IndexByteEncoder;\n        return __PRIVATE_FirestoreIndexValueWriter.bt.Pt(e, t.Ht(0 /* IndexKind.ASCENDING */)), \n        t.Wt();\n    }\n    /**\n     * Returns an encoded form of the document key that sorts based on the key\n     * ordering of the field index.\n     */    dn(e, t) {\n        const n = new __PRIVATE_IndexByteEncoder;\n        return __PRIVATE_FirestoreIndexValueWriter.bt.Pt(__PRIVATE_refValue(this.databaseId, t), n.Ht(function __PRIVATE_fieldIndexGetKeyOrder(e) {\n            const t = __PRIVATE_fieldIndexGetDirectionalSegments(e);\n            return 0 === t.length ? 0 /* IndexKind.ASCENDING */ : t[t.length - 1].kind;\n        }(e))), n.Wt();\n    }\n    /**\n     * Encodes the given field values according to the specification in `target`.\n     * For IN queries, a list of possible values is returned.\n     */    ln(e, t, n) {\n        if (null === n) return [];\n        let r = [];\n        r.push(new __PRIVATE_IndexByteEncoder);\n        let i = 0;\n        for (const s of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {\n            const e = n[i++];\n            for (const n of r) if (this.An(t, s.fieldPath) && isArray(e)) r = this.Rn(r, s, e); else {\n                const t = n.Ht(s.kind);\n                __PRIVATE_FirestoreIndexValueWriter.bt.Pt(e, t);\n            }\n        }\n        return this.Vn(r);\n    }\n    /**\n     * Encodes the given bounds according to the specification in `target`. For IN\n     * queries, a list of possible values is returned.\n     */    cn(e, t, n) {\n        return this.ln(e, t, n.position);\n    }\n    /** Returns the byte representation for the provided encoders. */    Vn(e) {\n        const t = [];\n        for (let n = 0; n < e.length; ++n) t[n] = e[n].Wt();\n        return t;\n    }\n    /**\n     * Creates a separate encoder for each element of an array.\n     *\n     * The method appends each value to all existing encoders (e.g. filter(\"a\",\n     * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n     * list of new encoders is returned.\n     */    Rn(e, t, n) {\n        const r = [ ...e ], i = [];\n        for (const e of n.arrayValue.values || []) for (const n of r) {\n            const r = new __PRIVATE_IndexByteEncoder;\n            r.seed(n.Wt()), __PRIVATE_FirestoreIndexValueWriter.bt.Pt(e, r.Ht(t.kind)), i.push(r);\n        }\n        return i;\n    }\n    An(e, t) {\n        return !!e.filters.find((e => e instanceof FieldFilter && e.field.isEqual(t) && (\"in\" /* Operator.IN */ === e.op || \"not-in\" /* Operator.NOT_IN */ === e.op)));\n    }\n    getFieldIndexes(e, t) {\n        const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e);\n        return (t ? n.G(\"collectionGroupIndex\", IDBKeyRange.bound(t, t)) : n.G()).next((e => {\n            const t = [];\n            return PersistencePromise.forEach(e, (e => r.get([ e.indexId, this.uid ]).next((n => {\n                t.push(function __PRIVATE_fromDbIndexConfiguration(e, t) {\n                    const n = t ? new IndexState(t.sequenceNumber, new IndexOffset(__PRIVATE_fromDbTimestamp(t.readTime), new DocumentKey(__PRIVATE_decodeResourcePath(t.documentKey)), t.largestBatchId)) : IndexState.empty(), r = e.fields.map((([e, t]) => new IndexSegment(FieldPath$1.fromServerFormat(e), t)));\n                    return new FieldIndex(e.indexId, e.collectionGroup, r, n);\n                }(e, n));\n            })))).next((() => t));\n        }));\n    }\n    getNextCollectionGroupToUpdate(e) {\n        return this.getFieldIndexes(e).next((e => 0 === e.length ? null : (e.sort(((e, t) => {\n            const n = e.indexState.sequenceNumber - t.indexState.sequenceNumber;\n            return 0 !== n ? n : __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup);\n        })), e[0].collectionGroup)));\n    }\n    updateCollectionGroup(e, t, n) {\n        const r = __PRIVATE_indexConfigurationStore(e), i = __PRIVATE_indexStateStore(e);\n        return this.mn(e).next((e => r.G(\"collectionGroupIndex\", IDBKeyRange.bound(t, t)).next((t => PersistencePromise.forEach(t, (t => i.put(__PRIVATE_toDbIndexState(t.indexId, this.user, e, n))))))));\n    }\n    updateIndexEntries(e, t) {\n        // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n        // it could be used across different IndexedDB transactions. As any cached\n        // data might be invalidated by other multi-tab clients, we can only trust\n        // data within a single IndexedDB transaction. We therefore add a cache\n        // here.\n        const n = new Map;\n        return PersistencePromise.forEach(t, ((t, r) => {\n            const i = n.get(t.collectionGroup);\n            return (i ? PersistencePromise.resolve(i) : this.getFieldIndexes(e, t.collectionGroup)).next((i => (n.set(t.collectionGroup, i), \n            PersistencePromise.forEach(i, (n => this.fn(e, t, n).next((t => {\n                const i = this.gn(r, n);\n                return t.isEqual(i) ? PersistencePromise.resolve() : this.pn(e, r, n, t, i);\n            })))))));\n        }));\n    }\n    yn(e, t, n, r) {\n        return __PRIVATE_indexEntriesStore(e).put({\n            indexId: r.indexId,\n            uid: this.uid,\n            arrayValue: r.arrayValue,\n            directionalValue: r.directionalValue,\n            orderedDocumentKey: this.dn(n, t.key),\n            documentKey: t.key.path.toArray()\n        });\n    }\n    wn(e, t, n, r) {\n        return __PRIVATE_indexEntriesStore(e).delete([ r.indexId, this.uid, r.arrayValue, r.directionalValue, this.dn(n, t.key), t.key.path.toArray() ]);\n    }\n    fn(e, t, n) {\n        const r = __PRIVATE_indexEntriesStore(e);\n        let i = new SortedSet(__PRIVATE_indexEntryComparator);\n        return r.Z({\n            index: \"documentKeyIndex\",\n            range: IDBKeyRange.only([ n.indexId, this.uid, this.dn(n, t) ])\n        }, ((e, r) => {\n            i = i.add(new __PRIVATE_IndexEntry(n.indexId, t, r.arrayValue, r.directionalValue));\n        })).next((() => i));\n    }\n    /** Creates the index entries for the given document. */    gn(e, t) {\n        let n = new SortedSet(__PRIVATE_indexEntryComparator);\n        const r = this.En(t, e);\n        if (null == r) return n;\n        const i = __PRIVATE_fieldIndexGetArraySegment(t);\n        if (null != i) {\n            const s = e.data.field(i.fieldPath);\n            if (isArray(s)) for (const i of s.arrayValue.values || []) n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, this.Pn(i), r));\n        } else n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, Ee, r));\n        return n;\n    }\n    /**\n     * Updates the index entries for the provided document by deleting entries\n     * that are no longer referenced in `newEntries` and adding all newly added\n     * entries.\n     */    pn(e, t, n, r, i) {\n        __PRIVATE_logDebug(\"IndexedDbIndexManager\", \"Updating index entries for document '%s'\", t.key);\n        const s = [];\n        return function __PRIVATE_diffSortedSets(e, t, n, r, i) {\n            const s = e.getIterator(), o = t.getIterator();\n            let _ = __PRIVATE_advanceIterator(s), a = __PRIVATE_advanceIterator(o);\n            // Walk through the two sets at the same time, using the ordering defined by\n            // `comparator`.\n            for (;_ || a; ) {\n                let e = !1, t = !1;\n                if (_ && a) {\n                    const r = n(_, a);\n                    r < 0 ? \n                    // The element was removed if the next element in our ordered\n                    // walkthrough is only in `before`.\n                    t = !0 : r > 0 && (\n                    // The element was added if the next element in our ordered walkthrough\n                    // is only in `after`.\n                    e = !0);\n                } else null != _ ? t = !0 : e = !0;\n                e ? (r(a), a = __PRIVATE_advanceIterator(o)) : t ? (i(_), _ = __PRIVATE_advanceIterator(s)) : (_ = __PRIVATE_advanceIterator(s), \n                a = __PRIVATE_advanceIterator(o));\n            }\n        }(r, i, __PRIVATE_indexEntryComparator, (\n        /* onAdd= */ r => {\n            s.push(this.yn(e, t, n, r));\n        }), (\n        /* onRemove= */ r => {\n            s.push(this.wn(e, t, n, r));\n        })), PersistencePromise.waitFor(s);\n    }\n    mn(e) {\n        let t = 1;\n        return __PRIVATE_indexStateStore(e).Z({\n            index: \"sequenceNumberIndex\",\n            reverse: !0,\n            range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])\n        }, ((e, n, r) => {\n            r.done(), t = n.sequenceNumber + 1;\n        })).next((() => t));\n    }\n    /**\n     * Returns a new set of IDB ranges that splits the existing range and excludes\n     * any values that match the `notInValue` from these ranges. As an example,\n     * '[foo > 2 && foo != 3]` becomes  `[foo > 2 && < 3, foo > 3]`.\n     */    createRange(e, t, n) {\n        // The notIn values need to be sorted and unique so that we can return a\n        // sorted set of non-overlapping ranges.\n        n = n.sort(((e, t) => __PRIVATE_indexEntryComparator(e, t))).filter(((e, t, n) => !t || 0 !== __PRIVATE_indexEntryComparator(e, n[t - 1])));\n        const r = [];\n        r.push(e);\n        for (const i of n) {\n            const n = __PRIVATE_indexEntryComparator(i, e), s = __PRIVATE_indexEntryComparator(i, t);\n            if (0 === n) \n            // `notInValue` is the lower bound. We therefore need to raise the bound\n            // to the next value.\n            r[0] = e.Jt(); else if (n > 0 && s < 0) \n            // `notInValue` is in the middle of the range\n            r.push(i), r.push(i.Jt()); else if (s > 0) \n            // `notInValue` (and all following values) are out of the range\n            break;\n        }\n        r.push(t);\n        const i = [];\n        for (let e = 0; e < r.length; e += 2) {\n            // If we encounter two bounds that will create an unmatchable key range,\n            // then we return an empty set of key ranges.\n            if (this.Sn(r[e], r[e + 1])) return [];\n            const t = [ r[e].indexId, this.uid, r[e].arrayValue, r[e].directionalValue, Ee, [] ], n = [ r[e + 1].indexId, this.uid, r[e + 1].arrayValue, r[e + 1].directionalValue, Ee, [] ];\n            i.push(IDBKeyRange.bound(t, n));\n        }\n        return i;\n    }\n    Sn(e, t) {\n        // If lower bound is greater than the upper bound, then the key\n        // range can never be matched.\n        return __PRIVATE_indexEntryComparator(e, t) > 0;\n    }\n    getMinOffsetFromCollectionGroup(e, t) {\n        return this.getFieldIndexes(e, t).next(__PRIVATE_getMinOffsetFromFieldIndexes);\n    }\n    getMinOffset(e, t) {\n        return PersistencePromise.mapArray(this.an(t), (t => this.un(e, t).next((e => e || fail())))).next(__PRIVATE_getMinOffsetFromFieldIndexes);\n    }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */ function __PRIVATE_collectionParentsStore(e) {\n    return __PRIVATE_getStore(e, \"collectionParents\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */ function __PRIVATE_indexEntriesStore(e) {\n    return __PRIVATE_getStore(e, \"indexEntries\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */ function __PRIVATE_indexConfigurationStore(e) {\n    return __PRIVATE_getStore(e, \"indexConfiguration\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */ function __PRIVATE_indexStateStore(e) {\n    return __PRIVATE_getStore(e, \"indexState\");\n}\n\nfunction __PRIVATE_getMinOffsetFromFieldIndexes(e) {\n    __PRIVATE_hardAssert(0 !== e.length);\n    let t = e[0].indexState.offset, n = t.largestBatchId;\n    for (let r = 1; r < e.length; r++) {\n        const i = e[r].indexState.offset;\n        __PRIVATE_indexOffsetComparator(i, t) < 0 && (t = i), n < i.largestBatchId && (n = i.largestBatchId);\n    }\n    return new IndexOffset(t.readTime, t.documentKey, n);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const de = {\n    didRun: !1,\n    sequenceNumbersCollected: 0,\n    targetsRemoved: 0,\n    documentsRemoved: 0\n};\n\nclass LruParams {\n    constructor(\n    // When we attempt to collect, we will only do so if the cache size is greater than this\n    // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n    e, \n    // The percentage of sequence numbers that we will attempt to collect\n    t, \n    // A cap on the total number of sequence numbers that will be collected. This prevents\n    // us from collecting a huge number of sequence numbers if the cache has grown very large.\n    n) {\n        this.cacheSizeCollectionThreshold = e, this.percentileToCollect = t, this.maximumSequenceNumbersToCollect = n;\n    }\n    static withCacheSize(e) {\n        return new LruParams(e, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nfunction removeMutationBatch(e, t, n) {\n    const r = e.store(\"mutations\"), i = e.store(\"documentMutations\"), s = [], o = IDBKeyRange.only(n.batchId);\n    let _ = 0;\n    const a = r.Z({\n        range: o\n    }, ((e, t, n) => (_++, n.delete())));\n    s.push(a.next((() => {\n        __PRIVATE_hardAssert(1 === _);\n    })));\n    const u = [];\n    for (const e of n.mutations) {\n        const r = __PRIVATE_newDbDocumentMutationKey(t, e.key.path, n.batchId);\n        s.push(i.delete(r)), u.push(e.key);\n    }\n    return PersistencePromise.waitFor(s).next((() => u));\n}\n\n/**\n * Returns an approximate size for the given document.\n */ function __PRIVATE_dbDocumentSize(e) {\n    if (!e) return 0;\n    let t;\n    if (e.document) t = e.document; else if (e.unknownDocument) t = e.unknownDocument; else {\n        if (!e.noDocument) throw fail();\n        t = e.noDocument;\n    }\n    return JSON.stringify(t).length;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A mutation queue for a specific user, backed by IndexedDB. */ LruParams.DEFAULT_COLLECTION_PERCENTILE = 10, \nLruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, LruParams.DEFAULT = new LruParams(41943040, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), \nLruParams.DISABLED = new LruParams(-1, 0, 0);\n\nclass __PRIVATE_IndexedDbMutationQueue {\n    constructor(\n    /**\n     * The normalized userId (e.g. null UID => \"\" userId) used to store /\n     * retrieve mutations.\n     */\n    e, t, n, r) {\n        this.userId = e, this.serializer = t, this.indexManager = n, this.referenceDelegate = r, \n        /**\n         * Caches the document keys for pending mutation batches. If the mutation\n         * has been removed from IndexedDb, the cached value may continue to\n         * be used to retrieve the batch's document keys. To remove a cached value\n         * locally, `removeCachedMutationKeys()` should be invoked either directly\n         * or through `removeMutationBatches()`.\n         *\n         * With multi-tab, when the primary client acknowledges or rejects a mutation,\n         * this cache is used by secondary clients to invalidate the local\n         * view of the documents that were previously affected by the mutation.\n         */\n        // PORTING NOTE: Multi-tab only.\n        this.bn = {};\n    }\n    /**\n     * Creates a new mutation queue for the given user.\n     * @param user - The user for which to create a mutation queue.\n     * @param serializer - The serializer to use when persisting to IndexedDb.\n     */    static lt(e, t, n, r) {\n        // TODO(mcg): Figure out what constraints there are on userIDs\n        // In particular, are there any reserved characters? are empty ids allowed?\n        // For the moment store these together in the same mutations table assuming\n        // that empty userIDs aren't allowed.\n        __PRIVATE_hardAssert(\"\" !== e.uid);\n        const i = e.isAuthenticated() ? e.uid : \"\";\n        return new __PRIVATE_IndexedDbMutationQueue(i, t, n, r);\n    }\n    checkEmpty(e) {\n        let t = !0;\n        const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);\n        return __PRIVATE_mutationsStore(e).Z({\n            index: \"userMutationsIndex\",\n            range: n\n        }, ((e, n, r) => {\n            t = !1, r.done();\n        })).next((() => t));\n    }\n    addMutationBatch(e, t, n, r) {\n        const i = __PRIVATE_documentMutationsStore(e), s = __PRIVATE_mutationsStore(e);\n        // The IndexedDb implementation in Chrome (and Firefox) does not handle\n        // compound indices that include auto-generated keys correctly. To ensure\n        // that the index entry is added correctly in all browsers, we perform two\n        // writes: The first write is used to retrieve the next auto-generated Batch\n        // ID, and the second write populates the index and stores the actual\n        // mutation batch.\n        // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n        // We write an empty object to obtain key\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        return s.add({}).next((o => {\n            __PRIVATE_hardAssert(\"number\" == typeof o);\n            const _ = new MutationBatch(o, t, n, r), a = function __PRIVATE_toDbMutationBatch(e, t, n) {\n                const r = n.baseMutations.map((t => toMutation(e.ct, t))), i = n.mutations.map((t => toMutation(e.ct, t)));\n                return {\n                    userId: t,\n                    batchId: n.batchId,\n                    localWriteTimeMs: n.localWriteTime.toMillis(),\n                    baseMutations: r,\n                    mutations: i\n                };\n            }(this.serializer, this.userId, _), u = [];\n            let c = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString())));\n            for (const e of r) {\n                const t = __PRIVATE_newDbDocumentMutationKey(this.userId, e.key.path, o);\n                c = c.add(e.key.path.popLast()), u.push(s.put(a)), u.push(i.put(t, O));\n            }\n            return c.forEach((t => {\n                u.push(this.indexManager.addToCollectionParentIndex(e, t));\n            })), e.addOnCommittedListener((() => {\n                this.bn[o] = _.keys();\n            })), PersistencePromise.waitFor(u).next((() => _));\n        }));\n    }\n    lookupMutationBatch(e, t) {\n        return __PRIVATE_mutationsStore(e).get(t).next((e => e ? (__PRIVATE_hardAssert(e.userId === this.userId), \n        __PRIVATE_fromDbMutationBatch(this.serializer, e)) : null));\n    }\n    /**\n     * Returns the document keys for the mutation batch with the given batchId.\n     * For primary clients, this method returns `null` after\n     * `removeMutationBatches()` has been called. Secondary clients return a\n     * cached result until `removeCachedMutationKeys()` is invoked.\n     */\n    // PORTING NOTE: Multi-tab only.\n    Dn(e, t) {\n        return this.bn[t] ? PersistencePromise.resolve(this.bn[t]) : this.lookupMutationBatch(e, t).next((e => {\n            if (e) {\n                const n = e.keys();\n                return this.bn[t] = n, n;\n            }\n            return null;\n        }));\n    }\n    getNextMutationBatchAfterBatchId(e, t) {\n        const n = t + 1, r = IDBKeyRange.lowerBound([ this.userId, n ]);\n        let i = null;\n        return __PRIVATE_mutationsStore(e).Z({\n            index: \"userMutationsIndex\",\n            range: r\n        }, ((e, t, r) => {\n            t.userId === this.userId && (__PRIVATE_hardAssert(t.batchId >= n), i = __PRIVATE_fromDbMutationBatch(this.serializer, t)), \n            r.done();\n        })).next((() => i));\n    }\n    getHighestUnacknowledgedBatchId(e) {\n        const t = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);\n        let n = -1;\n        return __PRIVATE_mutationsStore(e).Z({\n            index: \"userMutationsIndex\",\n            range: t,\n            reverse: !0\n        }, ((e, t, r) => {\n            n = t.batchId, r.done();\n        })).next((() => n));\n    }\n    getAllMutationBatches(e) {\n        const t = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);\n        return __PRIVATE_mutationsStore(e).G(\"userMutationsIndex\", t).next((e => e.map((e => __PRIVATE_fromDbMutationBatch(this.serializer, e)))));\n    }\n    getAllMutationBatchesAffectingDocumentKey(e, t) {\n        // Scan the document-mutation index starting with a prefix starting with\n        // the given documentKey.\n        const n = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), r = IDBKeyRange.lowerBound(n), i = [];\n        return __PRIVATE_documentMutationsStore(e).Z({\n            range: r\n        }, ((n, r, s) => {\n            const [o, _, a] = n, u = __PRIVATE_decodeResourcePath(_);\n            // Only consider rows matching exactly the specific key of\n            // interest. Note that because we order by path first, and we\n            // order terminators before path separators, we'll encounter all\n            // the index rows for documentKey contiguously. In particular, all\n            // the rows for documentKey will occur before any rows for\n            // documents nested in a subcollection beneath documentKey so we\n            // can stop as soon as we hit any such row.\n                        if (o === this.userId && t.path.isEqual(u)) \n            // Look up the mutation batch in the store.\n            return __PRIVATE_mutationsStore(e).get(a).next((e => {\n                if (!e) throw fail();\n                __PRIVATE_hardAssert(e.userId === this.userId), i.push(__PRIVATE_fromDbMutationBatch(this.serializer, e));\n            }));\n            s.done();\n        })).next((() => i));\n    }\n    getAllMutationBatchesAffectingDocumentKeys(e, t) {\n        let n = new SortedSet(__PRIVATE_primitiveComparator);\n        const r = [];\n        return t.forEach((t => {\n            const i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), s = IDBKeyRange.lowerBound(i), o = __PRIVATE_documentMutationsStore(e).Z({\n                range: s\n            }, ((e, r, i) => {\n                const [s, o, _] = e, a = __PRIVATE_decodeResourcePath(o);\n                // Only consider rows matching exactly the specific key of\n                // interest. Note that because we order by path first, and we\n                // order terminators before path separators, we'll encounter all\n                // the index rows for documentKey contiguously. In particular, all\n                // the rows for documentKey will occur before any rows for\n                // documents nested in a subcollection beneath documentKey so we\n                // can stop as soon as we hit any such row.\n                                s === this.userId && t.path.isEqual(a) ? n = n.add(_) : i.done();\n            }));\n            r.push(o);\n        })), PersistencePromise.waitFor(r).next((() => this.vn(e, n)));\n    }\n    getAllMutationBatchesAffectingQuery(e, t) {\n        const n = t.path, r = n.length + 1, i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, n), s = IDBKeyRange.lowerBound(i);\n        // Collect up unique batchIDs encountered during a scan of the index. Use a\n        // SortedSet to accumulate batch IDs so they can be traversed in order in a\n        // scan of the main table.\n        let o = new SortedSet(__PRIVATE_primitiveComparator);\n        return __PRIVATE_documentMutationsStore(e).Z({\n            range: s\n        }, ((e, t, i) => {\n            const [s, _, a] = e, u = __PRIVATE_decodeResourcePath(_);\n            s === this.userId && n.isPrefixOf(u) ? \n            // Rows with document keys more than one segment longer than the\n            // query path can't be matches. For example, a query on 'rooms'\n            // can't match the document /rooms/abc/messages/xyx.\n            // TODO(mcg): we'll need a different scanner when we implement\n            // ancestor queries.\n            u.length === r && (o = o.add(a)) : i.done();\n        })).next((() => this.vn(e, o)));\n    }\n    vn(e, t) {\n        const n = [], r = [];\n        // TODO(rockwood): Implement this using iterate.\n        return t.forEach((t => {\n            r.push(__PRIVATE_mutationsStore(e).get(t).next((e => {\n                if (null === e) throw fail();\n                __PRIVATE_hardAssert(e.userId === this.userId), n.push(__PRIVATE_fromDbMutationBatch(this.serializer, e));\n            })));\n        })), PersistencePromise.waitFor(r).next((() => n));\n    }\n    removeMutationBatch(e, t) {\n        return removeMutationBatch(e.ue, this.userId, t).next((n => (e.addOnCommittedListener((() => {\n            this.Cn(t.batchId);\n        })), PersistencePromise.forEach(n, (t => this.referenceDelegate.markPotentiallyOrphaned(e, t))))));\n    }\n    /**\n     * Clears the cached keys for a mutation batch. This method should be\n     * called by secondary clients after they process mutation updates.\n     *\n     * Note that this method does not have to be called from primary clients as\n     * the corresponding cache entries are cleared when an acknowledged or\n     * rejected batch is removed from the mutation queue.\n     */\n    // PORTING NOTE: Multi-tab only\n    Cn(e) {\n        delete this.bn[e];\n    }\n    performConsistencyCheck(e) {\n        return this.checkEmpty(e).next((t => {\n            if (!t) return PersistencePromise.resolve();\n            // Verify that there are no entries in the documentMutations index if\n            // the queue is empty.\n                        const n = IDBKeyRange.lowerBound(\n            /**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\n            function __PRIVATE_newDbDocumentMutationPrefixForUser(e) {\n                return [ e ];\n            }(this.userId)), r = [];\n            return __PRIVATE_documentMutationsStore(e).Z({\n                range: n\n            }, ((e, t, n) => {\n                if (e[0] === this.userId) {\n                    const t = __PRIVATE_decodeResourcePath(e[1]);\n                    r.push(t);\n                } else n.done();\n            })).next((() => {\n                __PRIVATE_hardAssert(0 === r.length);\n            }));\n        }));\n    }\n    containsKey(e, t) {\n        return __PRIVATE_mutationQueueContainsKey(e, this.userId, t);\n    }\n    // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n    /** Returns the mutation queue's metadata from IndexedDb. */\n    Fn(e) {\n        return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e => e || {\n            userId: this.userId,\n            lastAcknowledgedBatchId: -1,\n            lastStreamToken: \"\"\n        }));\n    }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n *         mutation for the given key.\n */ function __PRIVATE_mutationQueueContainsKey(e, t, n) {\n    const r = __PRIVATE_newDbDocumentMutationPrefixForPath(t, n.path), i = r[1], s = IDBKeyRange.lowerBound(r);\n    let o = !1;\n    return __PRIVATE_documentMutationsStore(e).Z({\n        range: s,\n        Y: !0\n    }, ((e, n, r) => {\n        const [s, _, /*batchID*/ a] = e;\n        s === t && _ === i && (o = !0), r.done();\n    })).next((() => o));\n}\n\n/** Returns true if any mutation queue contains the given document. */\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction __PRIVATE_mutationsStore(e) {\n    return __PRIVATE_getStore(e, \"mutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function __PRIVATE_documentMutationsStore(e) {\n    return __PRIVATE_getStore(e, \"documentMutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function __PRIVATE_mutationQueuesStore(e) {\n    return __PRIVATE_getStore(e, \"mutationQueues\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Offset to ensure non-overlapping target ids. */\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nclass __PRIVATE_TargetIdGenerator {\n    constructor(e) {\n        this.Mn = e;\n    }\n    next() {\n        return this.Mn += 2, this.Mn;\n    }\n    static xn() {\n        // The target cache generator must return '2' in its first call to `next()`\n        // as there is no differentiation in the protocol layer between an unset\n        // number and the number '0'. If we were to sent a target with target ID\n        // '0', the backend would consider it unset and replace it with its own ID.\n        return new __PRIVATE_TargetIdGenerator(0);\n    }\n    static On() {\n        // Sync engine assigns target IDs for limbo document detection.\n        return new __PRIVATE_TargetIdGenerator(-1);\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_IndexedDbTargetCache {\n    constructor(e, t) {\n        this.referenceDelegate = e, this.serializer = t;\n    }\n    // PORTING NOTE: We don't cache global metadata for the target cache, since\n    // some of it (in particular `highestTargetId`) can be modified by secondary\n    // tabs. We could perhaps be more granular (and e.g. still cache\n    // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n    // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n    // out to have a meaningful performance impact.\n    allocateTargetId(e) {\n        return this.Nn(e).next((t => {\n            const n = new __PRIVATE_TargetIdGenerator(t.highestTargetId);\n            return t.highestTargetId = n.next(), this.Bn(e, t).next((() => t.highestTargetId));\n        }));\n    }\n    getLastRemoteSnapshotVersion(e) {\n        return this.Nn(e).next((e => SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds, e.lastRemoteSnapshotVersion.nanoseconds))));\n    }\n    getHighestSequenceNumber(e) {\n        return this.Nn(e).next((e => e.highestListenSequenceNumber));\n    }\n    setTargetsMetadata(e, t, n) {\n        return this.Nn(e).next((r => (r.highestListenSequenceNumber = t, n && (r.lastRemoteSnapshotVersion = n.toTimestamp()), \n        t > r.highestListenSequenceNumber && (r.highestListenSequenceNumber = t), this.Bn(e, r))));\n    }\n    addTargetData(e, t) {\n        return this.Ln(e, t).next((() => this.Nn(e).next((n => (n.targetCount += 1, this.kn(t, n), \n        this.Bn(e, n))))));\n    }\n    updateTargetData(e, t) {\n        return this.Ln(e, t);\n    }\n    removeTargetData(e, t) {\n        return this.removeMatchingKeysForTargetId(e, t.targetId).next((() => __PRIVATE_targetsStore(e).delete(t.targetId))).next((() => this.Nn(e))).next((t => (__PRIVATE_hardAssert(t.targetCount > 0), \n        t.targetCount -= 1, this.Bn(e, t))));\n    }\n    /**\n     * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n     * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n     * Returns the number of targets removed.\n     */    removeTargets(e, t, n) {\n        let r = 0;\n        const i = [];\n        return __PRIVATE_targetsStore(e).Z(((s, o) => {\n            const _ = __PRIVATE_fromDbTarget(o);\n            _.sequenceNumber <= t && null === n.get(_.targetId) && (r++, i.push(this.removeTargetData(e, _)));\n        })).next((() => PersistencePromise.waitFor(i))).next((() => r));\n    }\n    /**\n     * Call provided function with each `TargetData` that we have cached.\n     */    forEachTarget(e, t) {\n        return __PRIVATE_targetsStore(e).Z(((e, n) => {\n            const r = __PRIVATE_fromDbTarget(n);\n            t(r);\n        }));\n    }\n    Nn(e) {\n        return __PRIVATE_globalTargetStore(e).get(\"targetGlobalKey\").next((e => (__PRIVATE_hardAssert(null !== e), \n        e)));\n    }\n    Bn(e, t) {\n        return __PRIVATE_globalTargetStore(e).put(\"targetGlobalKey\", t);\n    }\n    Ln(e, t) {\n        return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer, t));\n    }\n    /**\n     * In-place updates the provided metadata to account for values in the given\n     * TargetData. Saving is done separately. Returns true if there were any\n     * changes to the metadata.\n     */    kn(e, t) {\n        let n = !1;\n        return e.targetId > t.highestTargetId && (t.highestTargetId = e.targetId, n = !0), \n        e.sequenceNumber > t.highestListenSequenceNumber && (t.highestListenSequenceNumber = e.sequenceNumber, \n        n = !0), n;\n    }\n    getTargetCount(e) {\n        return this.Nn(e).next((e => e.targetCount));\n    }\n    getTargetData(e, t) {\n        // Iterating by the canonicalId may yield more than one result because\n        // canonicalId values are not required to be unique per target. This query\n        // depends on the queryTargets index to be efficient.\n        const n = __PRIVATE_canonifyTarget(t), r = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);\n        let i = null;\n        return __PRIVATE_targetsStore(e).Z({\n            range: r,\n            index: \"queryTargetsIndex\"\n        }, ((e, n, r) => {\n            const s = __PRIVATE_fromDbTarget(n);\n            // After finding a potential match, check that the target is\n            // actually equal to the requested target.\n                        __PRIVATE_targetEquals(t, s.target) && (i = s, r.done());\n        })).next((() => i));\n    }\n    addMatchingKeys(e, t, n) {\n        // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n        // IndexedDb.\n        const r = [], i = __PRIVATE_documentTargetStore(e);\n        return t.forEach((t => {\n            const s = __PRIVATE_encodeResourcePath(t.path);\n            r.push(i.put({\n                targetId: n,\n                path: s\n            })), r.push(this.referenceDelegate.addReference(e, n, t));\n        })), PersistencePromise.waitFor(r);\n    }\n    removeMatchingKeys(e, t, n) {\n        // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n        // IndexedDb.\n        const r = __PRIVATE_documentTargetStore(e);\n        return PersistencePromise.forEach(t, (t => {\n            const i = __PRIVATE_encodeResourcePath(t.path);\n            return PersistencePromise.waitFor([ r.delete([ n, i ]), this.referenceDelegate.removeReference(e, n, t) ]);\n        }));\n    }\n    removeMatchingKeysForTargetId(e, t) {\n        const n = __PRIVATE_documentTargetStore(e), r = IDBKeyRange.bound([ t ], [ t + 1 ], \n        /*lowerOpen=*/ !1, \n        /*upperOpen=*/ !0);\n        return n.delete(r);\n    }\n    getMatchingKeysForTargetId(e, t) {\n        const n = IDBKeyRange.bound([ t ], [ t + 1 ], \n        /*lowerOpen=*/ !1, \n        /*upperOpen=*/ !0), r = __PRIVATE_documentTargetStore(e);\n        let i = __PRIVATE_documentKeySet();\n        return r.Z({\n            range: n,\n            Y: !0\n        }, ((e, t, n) => {\n            const r = __PRIVATE_decodeResourcePath(e[1]), s = new DocumentKey(r);\n            i = i.add(s);\n        })).next((() => i));\n    }\n    containsKey(e, t) {\n        const n = __PRIVATE_encodeResourcePath(t.path), r = IDBKeyRange.bound([ n ], [ __PRIVATE_immediateSuccessor(n) ], \n        /*lowerOpen=*/ !1, \n        /*upperOpen=*/ !0);\n        let i = 0;\n        return __PRIVATE_documentTargetStore(e).Z({\n            index: \"documentTargetsIndex\",\n            Y: !0,\n            range: r\n        }, (([e, t], n, r) => {\n            // Having a sentinel row for a document does not count as containing that document;\n            // For the target cache, containing the document means the document is part of some\n            // target.\n            0 !== e && (i++, r.done());\n        })).next((() => i > 0));\n    }\n    /**\n     * Looks up a TargetData entry by target ID.\n     *\n     * @param targetId - The target ID of the TargetData entry to look up.\n     * @returns The cached TargetData entry, or null if the cache has no entry for\n     * the target.\n     */\n    // PORTING NOTE: Multi-tab only.\n    ut(e, t) {\n        return __PRIVATE_targetsStore(e).get(t).next((e => e ? __PRIVATE_fromDbTarget(e) : null));\n    }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */ function __PRIVATE_targetsStore(e) {\n    return __PRIVATE_getStore(e, \"targets\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */ function __PRIVATE_globalTargetStore(e) {\n    return __PRIVATE_getStore(e, \"targetGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */ function __PRIVATE_documentTargetStore(e) {\n    return __PRIVATE_getStore(e, \"targetDocuments\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function __PRIVATE_bufferEntryComparator([e, t], [n, r]) {\n    const i = __PRIVATE_primitiveComparator(e, n);\n    return 0 === i ? __PRIVATE_primitiveComparator(t, r) : i;\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */ class __PRIVATE_RollingSequenceNumberBuffer {\n    constructor(e) {\n        this.qn = e, this.buffer = new SortedSet(__PRIVATE_bufferEntryComparator), this.Qn = 0;\n    }\n    Kn() {\n        return ++this.Qn;\n    }\n    $n(e) {\n        const t = [ e, this.Kn() ];\n        if (this.buffer.size < this.qn) this.buffer = this.buffer.add(t); else {\n            const e = this.buffer.last();\n            __PRIVATE_bufferEntryComparator(t, e) < 0 && (this.buffer = this.buffer.delete(e).add(t));\n        }\n    }\n    get maxValue() {\n        // Guaranteed to be non-empty. If we decide we are not collecting any\n        // sequence numbers, nthSequenceNumber below short-circuits. If we have\n        // decided that we are collecting n sequence numbers, it's because n is some\n        // percentage of the existing sequence numbers. That means we should never\n        // be in a situation where we are collecting sequence numbers but don't\n        // actually have any.\n        return this.buffer.last()[0];\n    }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */ class __PRIVATE_LruScheduler {\n    constructor(e, t, n) {\n        this.garbageCollector = e, this.asyncQueue = t, this.localStore = n, this.Un = null;\n    }\n    start() {\n        -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Wn(6e4);\n    }\n    stop() {\n        this.Un && (this.Un.cancel(), this.Un = null);\n    }\n    get started() {\n        return null !== this.Un;\n    }\n    Wn(e) {\n        __PRIVATE_logDebug(\"LruGarbageCollector\", `Garbage collection scheduled in ${e}ms`), \n        this.Un = this.asyncQueue.enqueueAfterDelay(\"lru_garbage_collection\" /* TimerId.LruGarbageCollection */ , e, (async () => {\n            this.Un = null;\n            try {\n                await this.localStore.collectGarbage(this.garbageCollector);\n            } catch (e) {\n                __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(\"LruGarbageCollector\", \"Ignoring IndexedDB error during garbage collection: \", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n            }\n            await this.Wn(3e5);\n        }));\n    }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */ class __PRIVATE_LruGarbageCollectorImpl {\n    constructor(e, t) {\n        this.Gn = e, this.params = t;\n    }\n    calculateTargetCount(e, t) {\n        return this.Gn.zn(e).next((e => Math.floor(t / 100 * e)));\n    }\n    nthSequenceNumber(e, t) {\n        if (0 === t) return PersistencePromise.resolve(__PRIVATE_ListenSequence.ae);\n        const n = new __PRIVATE_RollingSequenceNumberBuffer(t);\n        return this.Gn.forEachTarget(e, (e => n.$n(e.sequenceNumber))).next((() => this.Gn.jn(e, (e => n.$n(e))))).next((() => n.maxValue));\n    }\n    removeTargets(e, t, n) {\n        return this.Gn.removeTargets(e, t, n);\n    }\n    removeOrphanedDocuments(e, t) {\n        return this.Gn.removeOrphanedDocuments(e, t);\n    }\n    collect(e, t) {\n        return -1 === this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug(\"LruGarbageCollector\", \"Garbage collection skipped; disabled\"), \n        PersistencePromise.resolve(de)) : this.getCacheSize(e).next((n => n < this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug(\"LruGarbageCollector\", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), \n        de) : this.Hn(e, t)));\n    }\n    getCacheSize(e) {\n        return this.Gn.getCacheSize(e);\n    }\n    Hn(e, t) {\n        let n, r, i, s, o, a, u;\n        const c = Date.now();\n        return this.calculateTargetCount(e, this.params.percentileToCollect).next((t => (\n        // Cap at the configured max\n        t > this.params.maximumSequenceNumbersToCollect ? (__PRIVATE_logDebug(\"LruGarbageCollector\", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`), \n        r = this.params.maximumSequenceNumbersToCollect) : r = t, s = Date.now(), this.nthSequenceNumber(e, r)))).next((r => (n = r, \n        o = Date.now(), this.removeTargets(e, n, t)))).next((t => (i = t, a = Date.now(), \n        this.removeOrphanedDocuments(e, n)))).next((e => {\n            if (u = Date.now(), __PRIVATE_getLogLevel() <= LogLevel.DEBUG) {\n                __PRIVATE_logDebug(\"LruGarbageCollector\", `LRU Garbage Collection\\n\\tCounted targets in ${s - c}ms\\n\\tDetermined least recently used ${r} in ` + (o - s) + \"ms\\n\" + `\\tRemoved ${i} targets in ` + (a - o) + \"ms\\n\" + `\\tRemoved ${e} documents in ` + (u - a) + \"ms\\n\" + `Total Duration: ${u - c}ms`);\n            }\n            return PersistencePromise.resolve({\n                didRun: !0,\n                sequenceNumbersCollected: r,\n                targetsRemoved: i,\n                documentsRemoved: e\n            });\n        }));\n    }\n}\n\nfunction __PRIVATE_newLruGarbageCollector(e, t) {\n    return new __PRIVATE_LruGarbageCollectorImpl(e, t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Provides LRU functionality for IndexedDB persistence. */ class __PRIVATE_IndexedDbLruDelegateImpl {\n    constructor(e, t) {\n        this.db = e, this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);\n    }\n    zn(e) {\n        const t = this.Jn(e);\n        return this.db.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t))));\n    }\n    Jn(e) {\n        let t = 0;\n        return this.jn(e, (e => {\n            t++;\n        })).next((() => t));\n    }\n    forEachTarget(e, t) {\n        return this.db.getTargetCache().forEachTarget(e, t);\n    }\n    jn(e, t) {\n        return this.Yn(e, ((e, n) => t(n)));\n    }\n    addReference(e, t, n) {\n        return __PRIVATE_writeSentinelKey(e, n);\n    }\n    removeReference(e, t, n) {\n        return __PRIVATE_writeSentinelKey(e, n);\n    }\n    removeTargets(e, t, n) {\n        return this.db.getTargetCache().removeTargets(e, t, n);\n    }\n    markPotentiallyOrphaned(e, t) {\n        return __PRIVATE_writeSentinelKey(e, t);\n    }\n    /**\n     * Returns true if anything would prevent this document from being garbage\n     * collected, given that the document in question is not present in any\n     * targets and has a sequence number less than or equal to the upper bound for\n     * the collection run.\n     */    Zn(e, t) {\n        return function __PRIVATE_mutationQueuesContainKey(e, t) {\n            let n = !1;\n            return __PRIVATE_mutationQueuesStore(e).X((r => __PRIVATE_mutationQueueContainsKey(e, r, t).next((e => (e && (n = !0), \n            PersistencePromise.resolve(!e)))))).next((() => n));\n        }(e, t);\n    }\n    removeOrphanedDocuments(e, t) {\n        const n = this.db.getRemoteDocumentCache().newChangeBuffer(), r = [];\n        let i = 0;\n        return this.Yn(e, ((s, o) => {\n            if (o <= t) {\n                const t = this.Zn(e, s).next((t => {\n                    if (!t) \n                    // Our size accounting requires us to read all documents before\n                    // removing them.\n                    return i++, n.getEntry(e, s).next((() => (n.removeEntry(s, SnapshotVersion.min()), \n                    __PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$1(e) {\n                        return [ 0, __PRIVATE_encodeResourcePath(e.path) ];\n                    }\n                    /**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */ (s)))));\n                }));\n                r.push(t);\n            }\n        })).next((() => PersistencePromise.waitFor(r))).next((() => n.apply(e))).next((() => i));\n    }\n    removeTarget(e, t) {\n        const n = t.withSequenceNumber(e.currentSequenceNumber);\n        return this.db.getTargetCache().updateTargetData(e, n);\n    }\n    updateLimboDocument(e, t) {\n        return __PRIVATE_writeSentinelKey(e, t);\n    }\n    /**\n     * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n     * means not a part of any target, so the only entry in the target-document index for\n     * that document will be the sentinel row (targetId 0), which will also have the sequence\n     * number for the last time the document was accessed.\n     */    Yn(e, t) {\n        const n = __PRIVATE_documentTargetStore(e);\n        let r, i = __PRIVATE_ListenSequence.ae;\n        return n.Z({\n            index: \"documentTargetsIndex\"\n        }, (([e, n], {path: s, sequenceNumber: o}) => {\n            0 === e ? (\n            // if nextToReport is valid, report it, this is a new key so the\n            // last one must not be a member of any targets.\n            i !== __PRIVATE_ListenSequence.ae && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i), \n            // set nextToReport to be this sequence number. It's the next one we\n            // might report, if we don't find any targets for this document.\n            // Note that the sequence number must be defined when the targetId\n            // is 0.\n            i = o, r = s) : \n            // set nextToReport to be invalid, we know we don't need to report\n            // this one since we found a target for it.\n            i = __PRIVATE_ListenSequence.ae;\n        })).next((() => {\n            // Since we report sequence numbers after getting to the next key, we\n            // need to check if the last key we iterated over was an orphaned\n            // document and report it.\n            i !== __PRIVATE_ListenSequence.ae && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i);\n        }));\n    }\n    getCacheSize(e) {\n        return this.db.getRemoteDocumentCache().getSize(e);\n    }\n}\n\nfunction __PRIVATE_writeSentinelKey(e, t) {\n    return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e, t) {\n        return {\n            targetId: 0,\n            path: __PRIVATE_encodeResourcePath(e.path),\n            sequenceNumber: t\n        };\n    }(t, e.currentSequenceNumber));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */ class RemoteDocumentChangeBuffer {\n    constructor() {\n        // A mapping of document key to the new cache entry that should be written.\n        this.changes = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))), this.changesApplied = !1;\n    }\n    /**\n     * Buffers a `RemoteDocumentCache.addEntry()` call.\n     *\n     * You can only modify documents that have already been retrieved via\n     * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n     */    addEntry(e) {\n        this.assertNotApplied(), this.changes.set(e.key, e);\n    }\n    /**\n     * Buffers a `RemoteDocumentCache.removeEntry()` call.\n     *\n     * You can only remove documents that have already been retrieved via\n     * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n     */    removeEntry(e, t) {\n        this.assertNotApplied(), this.changes.set(e, MutableDocument.newInvalidDocument(e).setReadTime(t));\n    }\n    /**\n     * Looks up an entry in the cache. The buffered changes will first be checked,\n     * and if no buffered change applies, this will forward to\n     * `RemoteDocumentCache.getEntry()`.\n     *\n     * @param transaction - The transaction in which to perform any persistence\n     *     operations.\n     * @param documentKey - The key of the entry to look up.\n     * @returns The cached document or an invalid document if we have nothing\n     * cached.\n     */    getEntry(e, t) {\n        this.assertNotApplied();\n        const n = this.changes.get(t);\n        return void 0 !== n ? PersistencePromise.resolve(n) : this.getFromCache(e, t);\n    }\n    /**\n     * Looks up several entries in the cache, forwarding to\n     * `RemoteDocumentCache.getEntry()`.\n     *\n     * @param transaction - The transaction in which to perform any persistence\n     *     operations.\n     * @param documentKeys - The keys of the entries to look up.\n     * @returns A map of cached documents, indexed by key. If an entry cannot be\n     *     found, the corresponding key will be mapped to an invalid document.\n     */    getEntries(e, t) {\n        return this.getAllFromCache(e, t);\n    }\n    /**\n     * Applies buffered changes to the underlying RemoteDocumentCache, using\n     * the provided transaction.\n     */    apply(e) {\n        return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(e);\n    }\n    /** Helper to assert this.changes is not null  */    assertNotApplied() {}\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */ class __PRIVATE_IndexedDbRemoteDocumentCacheImpl {\n    constructor(e) {\n        this.serializer = e;\n    }\n    setIndexManager(e) {\n        this.indexManager = e;\n    }\n    /**\n     * Adds the supplied entries to the cache.\n     *\n     * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n     * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n     */    addEntry(e, t, n) {\n        return __PRIVATE_remoteDocumentsStore(e).put(n);\n    }\n    /**\n     * Removes a document from the cache.\n     *\n     * All calls of `removeEntry`  are required to go through the RemoteDocumentChangeBuffer\n     * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n     */    removeEntry(e, t, n) {\n        return __PRIVATE_remoteDocumentsStore(e).delete(\n        /**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\n        function __PRIVATE_dbReadTimeKey(e, t) {\n            const n = e.path.toArray();\n            return [ \n            /* prefix path */ n.slice(0, n.length - 2), \n            /* collection id */ n[n.length - 2], __PRIVATE_toDbTimestampKey(t), \n            /* document id */ n[n.length - 1] ];\n        }\n        /**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */ (t, n));\n    }\n    /**\n     * Updates the current cache size.\n     *\n     * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n     * cache's metadata.\n     */    updateMetadata(e, t) {\n        return this.getMetadata(e).next((n => (n.byteSize += t, this.Xn(e, n))));\n    }\n    getEntry(e, t) {\n        let n = MutableDocument.newInvalidDocument(t);\n        return __PRIVATE_remoteDocumentsStore(e).Z({\n            index: \"documentKeyIndex\",\n            range: IDBKeyRange.only(__PRIVATE_dbKey(t))\n        }, ((e, r) => {\n            n = this.er(t, r);\n        })).next((() => n));\n    }\n    /**\n     * Looks up an entry in the cache.\n     *\n     * @param documentKey - The key of the entry to look up.\n     * @returns The cached document entry and its size.\n     */    tr(e, t) {\n        let n = {\n            size: 0,\n            document: MutableDocument.newInvalidDocument(t)\n        };\n        return __PRIVATE_remoteDocumentsStore(e).Z({\n            index: \"documentKeyIndex\",\n            range: IDBKeyRange.only(__PRIVATE_dbKey(t))\n        }, ((e, r) => {\n            n = {\n                document: this.er(t, r),\n                size: __PRIVATE_dbDocumentSize(r)\n            };\n        })).next((() => n));\n    }\n    getEntries(e, t) {\n        let n = __PRIVATE_mutableDocumentMap();\n        return this.nr(e, t, ((e, t) => {\n            const r = this.er(e, t);\n            n = n.insert(e, r);\n        })).next((() => n));\n    }\n    /**\n     * Looks up several entries in the cache.\n     *\n     * @param documentKeys - The set of keys entries to look up.\n     * @returns A map of documents indexed by key and a map of sizes indexed by\n     *     key (zero if the document does not exist).\n     */    rr(e, t) {\n        let n = __PRIVATE_mutableDocumentMap(), r = new SortedMap(DocumentKey.comparator);\n        return this.nr(e, t, ((e, t) => {\n            const i = this.er(e, t);\n            n = n.insert(e, i), r = r.insert(e, __PRIVATE_dbDocumentSize(t));\n        })).next((() => ({\n            documents: n,\n            ir: r\n        })));\n    }\n    nr(e, t, n) {\n        if (t.isEmpty()) return PersistencePromise.resolve();\n        let r = new SortedSet(__PRIVATE_dbKeyComparator);\n        t.forEach((e => r = r.add(e)));\n        const i = IDBKeyRange.bound(__PRIVATE_dbKey(r.first()), __PRIVATE_dbKey(r.last())), s = r.getIterator();\n        let o = s.getNext();\n        return __PRIVATE_remoteDocumentsStore(e).Z({\n            index: \"documentKeyIndex\",\n            range: i\n        }, ((e, t, r) => {\n            const i = DocumentKey.fromSegments([ ...t.prefixPath, t.collectionGroup, t.documentId ]);\n            // Go through keys not found in cache.\n                        for (;o && __PRIVATE_dbKeyComparator(o, i) < 0; ) n(o, null), o = s.getNext();\n            o && o.isEqual(i) && (\n            // Key found in cache.\n            n(o, t), o = s.hasNext() ? s.getNext() : null), \n            // Skip to the next key (if there is one).\n            o ? r.W(__PRIVATE_dbKey(o)) : r.done();\n        })).next((() => {\n            // The rest of the keys are not in the cache. One case where `iterate`\n            // above won't go through them is when the cache is empty.\n            for (;o; ) n(o, null), o = s.hasNext() ? s.getNext() : null;\n        }));\n    }\n    getDocumentsMatchingQuery(e, t, n, r) {\n        const i = t.path, s = [ i.popLast().toArray(), i.lastSegment(), __PRIVATE_toDbTimestampKey(n.readTime), n.documentKey.path.isEmpty() ? \"\" : n.documentKey.path.lastSegment() ], o = [ i.popLast().toArray(), i.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], \"\" ];\n        return __PRIVATE_remoteDocumentsStore(e).G(IDBKeyRange.bound(s, o, !0)).next((e => {\n            let n = __PRIVATE_mutableDocumentMap();\n            for (const i of e) {\n                const e = this.er(DocumentKey.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i);\n                e.isFoundDocument() && (__PRIVATE_queryMatches(t, e) || r.has(e.key)) && (\n                // Either the document matches the given query, or it is mutated.\n                n = n.insert(e.key, e));\n            }\n            return n;\n        }));\n    }\n    getAllFromCollectionGroup(e, t, n, r) {\n        let i = __PRIVATE_mutableDocumentMap();\n        const s = __PRIVATE_dbCollectionGroupKey(t, n), o = __PRIVATE_dbCollectionGroupKey(t, IndexOffset.max());\n        return __PRIVATE_remoteDocumentsStore(e).Z({\n            index: \"collectionGroupIndex\",\n            range: IDBKeyRange.bound(s, o, !0)\n        }, ((e, t, n) => {\n            const s = this.er(DocumentKey.fromSegments(t.prefixPath.concat(t.collectionGroup, t.documentId)), t);\n            i = i.insert(s.key, s), i.size === r && n.done();\n        })).next((() => i));\n    }\n    newChangeBuffer(e) {\n        return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this, !!e && e.trackRemovals);\n    }\n    getSize(e) {\n        return this.getMetadata(e).next((e => e.byteSize));\n    }\n    getMetadata(e) {\n        return __PRIVATE_documentGlobalStore(e).get(\"remoteDocumentGlobalKey\").next((e => (__PRIVATE_hardAssert(!!e), \n        e)));\n    }\n    Xn(e, t) {\n        return __PRIVATE_documentGlobalStore(e).put(\"remoteDocumentGlobalKey\", t);\n    }\n    /**\n     * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n     * the document corresponds to the format used for sentinel deletes).\n     */    er(e, t) {\n        if (t) {\n            const e = __PRIVATE_fromDbRemoteDocument(this.serializer, t);\n            // Whether the document is a sentinel removal and should only be used in the\n            // `getNewDocumentChanges()`\n                        if (!(e.isNoDocument() && e.version.isEqual(SnapshotVersion.min()))) return e;\n        }\n        return MutableDocument.newInvalidDocument(e);\n    }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */ function __PRIVATE_newIndexedDbRemoteDocumentCache(e) {\n    return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */ class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n    /**\n     * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n     * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n     * `getNewDocumentChanges()`.\n     */\n    constructor(e, t) {\n        super(), this.sr = e, this.trackRemovals = t, \n        // A map of document sizes and read times prior to applying the changes in\n        // this buffer.\n        this._r = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t)));\n    }\n    applyChanges(e) {\n        const t = [];\n        let n = 0, r = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString())));\n        return this.changes.forEach(((i, s) => {\n            const o = this._r.get(i);\n            if (t.push(this.sr.removeEntry(e, i, o.readTime)), s.isValidDocument()) {\n                const _ = __PRIVATE_toDbRemoteDocument(this.sr.serializer, s);\n                r = r.add(i.path.popLast());\n                const a = __PRIVATE_dbDocumentSize(_);\n                n += a - o.size, t.push(this.sr.addEntry(e, i, _));\n            } else if (n -= o.size, this.trackRemovals) {\n                // In order to track removals, we store a \"sentinel delete\" in the\n                // RemoteDocumentCache. This entry is represented by a NoDocument\n                // with a version of 0 and ignored by `maybeDecodeDocument()` but\n                // preserved in `getNewDocumentChanges()`.\n                const n = __PRIVATE_toDbRemoteDocument(this.sr.serializer, s.convertToNoDocument(SnapshotVersion.min()));\n                t.push(this.sr.addEntry(e, i, n));\n            }\n        })), r.forEach((n => {\n            t.push(this.sr.indexManager.addToCollectionParentIndex(e, n));\n        })), t.push(this.sr.updateMetadata(e, n)), PersistencePromise.waitFor(t);\n    }\n    getFromCache(e, t) {\n        // Record the size of everything we load from the cache so we can compute a delta later.\n        return this.sr.tr(e, t).next((e => (this._r.set(t, {\n            size: e.size,\n            readTime: e.document.readTime\n        }), e.document)));\n    }\n    getAllFromCache(e, t) {\n        // Record the size of everything we load from the cache so we can compute\n        // a delta later.\n        return this.sr.rr(e, t).next((({documents: e, ir: t}) => (\n        // Note: `getAllFromCache` returns two maps instead of a single map from\n        // keys to `DocumentSizeEntry`s. This is to allow returning the\n        // `MutableDocumentMap` directly, without a conversion.\n        t.forEach(((t, n) => {\n            this._r.set(t, {\n                size: n,\n                readTime: e.get(t).readTime\n            });\n        })), e)));\n    }\n}\n\nfunction __PRIVATE_documentGlobalStore(e) {\n    return __PRIVATE_getStore(e, \"remoteDocumentGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */ function __PRIVATE_remoteDocumentsStore(e) {\n    return __PRIVATE_getStore(e, \"remoteDocumentsV14\");\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */ function __PRIVATE_dbKey(e) {\n    const t = e.path.toArray();\n    return [ \n    /* prefix path */ t.slice(0, t.length - 2), \n    /* collection id */ t[t.length - 2], \n    /* document id */ t[t.length - 1] ];\n}\n\nfunction __PRIVATE_dbCollectionGroupKey(e, t) {\n    const n = t.documentKey.path.toArray();\n    return [ \n    /* collection id */ e, __PRIVATE_toDbTimestampKey(t.readTime), \n    /* prefix path */ n.slice(0, n.length - 2), \n    /* document id */ n.length > 0 ? n[n.length - 1] : \"\" ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */ function __PRIVATE_dbKeyComparator(e, t) {\n    const n = e.path.toArray(), r = t.path.toArray();\n    // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n    let i = 0;\n    for (let e = 0; e < n.length - 2 && e < r.length - 2; ++e) if (i = __PRIVATE_primitiveComparator(n[e], r[e]), \n    i) return i;\n    return i = __PRIVATE_primitiveComparator(n.length, r.length), i || (i = __PRIVATE_primitiveComparator(n[n.length - 2], r[r.length - 2]), \n    i || __PRIVATE_primitiveComparator(n[n.length - 1], r[r.length - 1]));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Schema Version for the Web client:\n * 1.  Initial version including Mutation Queue, Query Cache, and Remote\n *     Document Cache\n * 2.  Used to ensure a targetGlobal object exists and add targetCount to it. No\n *     longer required because migration 3 unconditionally clears it.\n * 3.  Dropped and re-created Query Cache to deal with cache corruption related\n *     to limbo resolution. Addresses\n *     https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4.  Multi-Tab Support.\n * 5.  Removal of held write acks.\n * 6.  Create document global for tracking document cache size.\n * 7.  Ensure every cached document has a sentinel row with a sequence number.\n * 8.  Add collection-parent index for Collection Group queries.\n * 9.  Change RemoteDocumentChanges store to be keyed by readTime rather than\n *     an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n *     document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nclass OverlayedDocument {\n    constructor(e, \n    /**\n     * The fields that are locally mutated by patch mutations.\n     *\n     * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n     * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n     */\n    t) {\n        this.overlayedDocument = e, this.mutatedFields = t;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */ class LocalDocumentsView {\n    constructor(e, t, n, r) {\n        this.remoteDocumentCache = e, this.mutationQueue = t, this.documentOverlayCache = n, \n        this.indexManager = r;\n    }\n    /**\n     * Get the local view of the document identified by `key`.\n     *\n     * @returns Local view of the document or null if we don't have any cached\n     * state for it.\n     */    getDocument(e, t) {\n        let n = null;\n        return this.documentOverlayCache.getOverlay(e, t).next((r => (n = r, this.remoteDocumentCache.getEntry(e, t)))).next((e => (null !== n && __PRIVATE_mutationApplyToLocalView(n.mutation, e, FieldMask.empty(), Timestamp.now()), \n        e)));\n    }\n    /**\n     * Gets the local view of the documents identified by `keys`.\n     *\n     * If we don't have cached state for a document in `keys`, a NoDocument will\n     * be stored for that key in the resulting set.\n     */    getDocuments(e, t) {\n        return this.remoteDocumentCache.getEntries(e, t).next((t => this.getLocalViewOfDocuments(e, t, __PRIVATE_documentKeySet()).next((() => t))));\n    }\n    /**\n     * Similar to `getDocuments`, but creates the local view from the given\n     * `baseDocs` without retrieving documents from the local store.\n     *\n     * @param transaction - The transaction this operation is scoped to.\n     * @param docs - The documents to apply local mutations to get the local views.\n     * @param existenceStateChanged - The set of document keys whose existence state\n     *   is changed. This is useful to determine if some documents overlay needs\n     *   to be recalculated.\n     */    getLocalViewOfDocuments(e, t, n = __PRIVATE_documentKeySet()) {\n        const r = __PRIVATE_newOverlayMap();\n        return this.populateOverlays(e, r, t).next((() => this.computeViews(e, t, r, n).next((e => {\n            let t = documentMap();\n            return e.forEach(((e, n) => {\n                t = t.insert(e, n.overlayedDocument);\n            })), t;\n        }))));\n    }\n    /**\n     * Gets the overlayed documents for the given document map, which will include\n     * the local view of those documents and a `FieldMask` indicating which fields\n     * are mutated locally, `null` if overlay is a Set or Delete mutation.\n     */    getOverlayedDocuments(e, t) {\n        const n = __PRIVATE_newOverlayMap();\n        return this.populateOverlays(e, n, t).next((() => this.computeViews(e, t, n, __PRIVATE_documentKeySet())));\n    }\n    /**\n     * Fetches the overlays for {@code docs} and adds them to provided overlay map\n     * if the map does not already contain an entry for the given document key.\n     */    populateOverlays(e, t, n) {\n        const r = [];\n        return n.forEach((e => {\n            t.has(e) || r.push(e);\n        })), this.documentOverlayCache.getOverlays(e, r).next((e => {\n            e.forEach(((e, n) => {\n                t.set(e, n);\n            }));\n        }));\n    }\n    /**\n     * Computes the local view for the given documents.\n     *\n     * @param docs - The documents to compute views for. It also has the base\n     *   version of the documents.\n     * @param overlays - The overlays that need to be applied to the given base\n     *   version of the documents.\n     * @param existenceStateChanged - A set of documents whose existence states\n     *   might have changed. This is used to determine if we need to re-calculate\n     *   overlays from mutation queues.\n     * @return A map represents the local documents view.\n     */    computeViews(e, t, n, r) {\n        let i = __PRIVATE_mutableDocumentMap();\n        const s = __PRIVATE_newDocumentKeyMap(), o = function __PRIVATE_newOverlayedDocumentMap() {\n            return __PRIVATE_newDocumentKeyMap();\n        }();\n        return t.forEach(((e, t) => {\n            const o = n.get(t.key);\n            // Recalculate an overlay if the document's existence state changed due to\n            // a remote event *and* the overlay is a PatchMutation. This is because\n            // document existence state can change if some patch mutation's\n            // preconditions are met.\n            // NOTE: we recalculate when `overlay` is undefined as well, because there\n            // might be a patch mutation whose precondition does not match before the\n            // change (hence overlay is undefined), but would now match.\n                        r.has(t.key) && (void 0 === o || o.mutation instanceof __PRIVATE_PatchMutation) ? i = i.insert(t.key, t) : void 0 !== o ? (s.set(t.key, o.mutation.getFieldMask()), \n            __PRIVATE_mutationApplyToLocalView(o.mutation, t, o.mutation.getFieldMask(), Timestamp.now())) : \n            // no overlay exists\n            // Using EMPTY to indicate there is no overlay for the document.\n            s.set(t.key, FieldMask.empty());\n        })), this.recalculateAndSaveOverlays(e, i).next((e => (e.forEach(((e, t) => s.set(e, t))), \n        t.forEach(((e, t) => {\n            var n;\n            return o.set(e, new OverlayedDocument(t, null !== (n = s.get(e)) && void 0 !== n ? n : null));\n        })), o)));\n    }\n    recalculateAndSaveOverlays(e, t) {\n        const n = __PRIVATE_newDocumentKeyMap();\n        // A reverse lookup map from batch id to the documents within that batch.\n                let r = new SortedMap(((e, t) => e - t)), i = __PRIVATE_documentKeySet();\n        return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e, t).next((e => {\n            for (const i of e) i.keys().forEach((e => {\n                const s = t.get(e);\n                if (null === s) return;\n                let o = n.get(e) || FieldMask.empty();\n                o = i.applyToLocalView(s, o), n.set(e, o);\n                const _ = (r.get(i.batchId) || __PRIVATE_documentKeySet()).add(e);\n                r = r.insert(i.batchId, _);\n            }));\n        })).next((() => {\n            const s = [], o = r.getReverseIterator();\n            // Iterate in descending order of batch IDs, and skip documents that are\n            // already saved.\n                        for (;o.hasNext(); ) {\n                const r = o.getNext(), _ = r.key, a = r.value, u = __PRIVATE_newMutationMap();\n                a.forEach((e => {\n                    if (!i.has(e)) {\n                        const r = __PRIVATE_calculateOverlayMutation(t.get(e), n.get(e));\n                        null !== r && u.set(e, r), i = i.add(e);\n                    }\n                })), s.push(this.documentOverlayCache.saveOverlays(e, _, u));\n            }\n            return PersistencePromise.waitFor(s);\n        })).next((() => n));\n    }\n    /**\n     * Recalculates overlays by reading the documents from remote document cache\n     * first, and saves them after they are calculated.\n     */    recalculateAndSaveOverlaysForDocumentKeys(e, t) {\n        return this.remoteDocumentCache.getEntries(e, t).next((t => this.recalculateAndSaveOverlays(e, t)));\n    }\n    /**\n     * Performs a query against the local view of all documents.\n     *\n     * @param transaction - The persistence transaction.\n     * @param query - The query to match documents against.\n     * @param offset - Read time and key to start scanning by (exclusive).\n     */    getDocumentsMatchingQuery(e, t, n) {\n        /**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\n        return function __PRIVATE_isDocumentQuery$1(e) {\n            return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length;\n        }(t) ? this.getDocumentsMatchingDocumentQuery(e, t.path) : __PRIVATE_isCollectionGroupQuery(t) ? this.getDocumentsMatchingCollectionGroupQuery(e, t, n) : this.getDocumentsMatchingCollectionQuery(e, t, n);\n    }\n    /**\n     * Given a collection group, returns the next documents that follow the provided offset, along\n     * with an updated batch ID.\n     *\n     * <p>The documents returned by this method are ordered by remote version from the provided\n     * offset. If there are no more remote documents after the provided offset, documents with\n     * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n     * returned together, the total number of documents returned can exceed {@code count}.\n     *\n     * @param transaction\n     * @param collectionGroup The collection group for the documents.\n     * @param offset The offset to index into.\n     * @param count The number of documents to return\n     * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n     */    getNextDocuments(e, t, n, r) {\n        return this.remoteDocumentCache.getAllFromCollectionGroup(e, t, n, r).next((i => {\n            const s = r - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(e, t, n.largestBatchId, r - i.size) : PersistencePromise.resolve(__PRIVATE_newOverlayMap());\n            // The callsite will use the largest batch ID together with the latest read time to create\n            // a new index offset. Since we only process batch IDs if all remote documents have been read,\n            // no overlay will increase the overall read time. This is why we only need to special case\n            // the batch id.\n                        let o = -1, _ = i;\n            return s.next((t => PersistencePromise.forEach(t, ((t, n) => (o < n.largestBatchId && (o = n.largestBatchId), \n            i.get(t) ? PersistencePromise.resolve() : this.remoteDocumentCache.getEntry(e, t).next((e => {\n                _ = _.insert(t, e);\n            }))))).next((() => this.populateOverlays(e, t, i))).next((() => this.computeViews(e, _, t, __PRIVATE_documentKeySet()))).next((e => ({\n                batchId: o,\n                changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e)\n            })))));\n        }));\n    }\n    getDocumentsMatchingDocumentQuery(e, t) {\n        // Just do a simple document lookup.\n        return this.getDocument(e, new DocumentKey(t)).next((e => {\n            let t = documentMap();\n            return e.isFoundDocument() && (t = t.insert(e.key, e)), t;\n        }));\n    }\n    getDocumentsMatchingCollectionGroupQuery(e, t, n) {\n        const r = t.collectionGroup;\n        let i = documentMap();\n        return this.indexManager.getCollectionParents(e, r).next((s => PersistencePromise.forEach(s, (s => {\n            const o = function __PRIVATE_asCollectionQueryAtPath(e, t) {\n                return new __PRIVATE_QueryImpl(t, \n                /*collectionGroup=*/ null, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt);\n            }(t, s.child(r));\n            return this.getDocumentsMatchingCollectionQuery(e, o, n).next((e => {\n                e.forEach(((e, t) => {\n                    i = i.insert(e, t);\n                }));\n            }));\n        })).next((() => i))));\n    }\n    getDocumentsMatchingCollectionQuery(e, t, n) {\n        // Query the remote documents and overlay mutations.\n        let r;\n        return this.documentOverlayCache.getOverlaysForCollection(e, t.path, n.largestBatchId).next((i => (r = i, \n        this.remoteDocumentCache.getDocumentsMatchingQuery(e, t, n, r)))).next((e => {\n            // As documents might match the query because of their overlay we need to\n            // include documents for all overlays in the initial document set.\n            r.forEach(((t, n) => {\n                const r = n.getKey();\n                null === e.get(r) && (e = e.insert(r, MutableDocument.newInvalidDocument(r)));\n            }));\n            // Apply the overlays and match against the query.\n            let n = documentMap();\n            return e.forEach(((e, i) => {\n                const s = r.get(e);\n                void 0 !== s && __PRIVATE_mutationApplyToLocalView(s.mutation, i, FieldMask.empty(), Timestamp.now()), \n                // Finally, insert the documents that still match the query\n                __PRIVATE_queryMatches(t, i) && (n = n.insert(e, i));\n            })), n;\n        }));\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_MemoryBundleCache {\n    constructor(e) {\n        this.serializer = e, this.ar = new Map, this.ur = new Map;\n    }\n    getBundleMetadata(e, t) {\n        return PersistencePromise.resolve(this.ar.get(t));\n    }\n    saveBundleMetadata(e, t) {\n        return this.ar.set(t.id, \n        /** Decodes a BundleMetadata proto into a BundleMetadata object. */\n        function __PRIVATE_fromBundleMetadata(e) {\n            return {\n                id: e.id,\n                version: e.version,\n                createTime: __PRIVATE_fromVersion(e.createTime)\n            };\n        }(t)), PersistencePromise.resolve();\n    }\n    getNamedQuery(e, t) {\n        return PersistencePromise.resolve(this.ur.get(t));\n    }\n    saveNamedQuery(e, t) {\n        return this.ur.set(t.name, function __PRIVATE_fromProtoNamedQuery(e) {\n            return {\n                name: e.name,\n                query: __PRIVATE_fromBundledQuery(e.bundledQuery),\n                readTime: __PRIVATE_fromVersion(e.readTime)\n            };\n        }(t)), PersistencePromise.resolve();\n    }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */ class __PRIVATE_MemoryDocumentOverlayCache {\n    constructor() {\n        // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n        // for the overlay and the overlay itself.\n        this.overlays = new SortedMap(DocumentKey.comparator), this.cr = new Map;\n    }\n    getOverlay(e, t) {\n        return PersistencePromise.resolve(this.overlays.get(t));\n    }\n    getOverlays(e, t) {\n        const n = __PRIVATE_newOverlayMap();\n        return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => {\n            null !== e && n.set(t, e);\n        })))).next((() => n));\n    }\n    saveOverlays(e, t, n) {\n        return n.forEach(((n, r) => {\n            this.ht(e, t, r);\n        })), PersistencePromise.resolve();\n    }\n    removeOverlaysForBatchId(e, t, n) {\n        const r = this.cr.get(n);\n        return void 0 !== r && (r.forEach((e => this.overlays = this.overlays.remove(e))), \n        this.cr.delete(n)), PersistencePromise.resolve();\n    }\n    getOverlaysForCollection(e, t, n) {\n        const r = __PRIVATE_newOverlayMap(), i = t.length + 1, s = new DocumentKey(t.child(\"\")), o = this.overlays.getIteratorFrom(s);\n        for (;o.hasNext(); ) {\n            const e = o.getNext().value, s = e.getKey();\n            if (!t.isPrefixOf(s.path)) break;\n            // Documents from sub-collections\n                        s.path.length === i && (e.largestBatchId > n && r.set(e.getKey(), e));\n        }\n        return PersistencePromise.resolve(r);\n    }\n    getOverlaysForCollectionGroup(e, t, n, r) {\n        let i = new SortedMap(((e, t) => e - t));\n        const s = this.overlays.getIterator();\n        for (;s.hasNext(); ) {\n            const e = s.getNext().value;\n            if (e.getKey().getCollectionGroup() === t && e.largestBatchId > n) {\n                let t = i.get(e.largestBatchId);\n                null === t && (t = __PRIVATE_newOverlayMap(), i = i.insert(e.largestBatchId, t)), \n                t.set(e.getKey(), e);\n            }\n        }\n        const o = __PRIVATE_newOverlayMap(), _ = i.getIterator();\n        for (;_.hasNext(); ) {\n            if (_.getNext().value.forEach(((e, t) => o.set(e, t))), o.size() >= r) break;\n        }\n        return PersistencePromise.resolve(o);\n    }\n    ht(e, t, n) {\n        // Remove the association of the overlay to its batch id.\n        const r = this.overlays.get(n.key);\n        if (null !== r) {\n            const e = this.cr.get(r.largestBatchId).delete(n.key);\n            this.cr.set(r.largestBatchId, e);\n        }\n        this.overlays = this.overlays.insert(n.key, new Overlay(t, n));\n        // Create the association of this overlay to the given largestBatchId.\n        let i = this.cr.get(t);\n        void 0 === i && (i = __PRIVATE_documentKeySet(), this.cr.set(t, i)), this.cr.set(t, i.add(n.key));\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */ class __PRIVATE_ReferenceSet {\n    constructor() {\n        // A set of outstanding references to a document sorted by key.\n        this.lr = new SortedSet(__PRIVATE_DocReference.hr), \n        // A set of outstanding references to a document sorted by target id.\n        this.Pr = new SortedSet(__PRIVATE_DocReference.Ir);\n    }\n    /** Returns true if the reference set contains no references. */    isEmpty() {\n        return this.lr.isEmpty();\n    }\n    /** Adds a reference to the given document key for the given ID. */    addReference(e, t) {\n        const n = new __PRIVATE_DocReference(e, t);\n        this.lr = this.lr.add(n), this.Pr = this.Pr.add(n);\n    }\n    /** Add references to the given document keys for the given ID. */    Tr(e, t) {\n        e.forEach((e => this.addReference(e, t)));\n    }\n    /**\n     * Removes a reference to the given document key for the given\n     * ID.\n     */    removeReference(e, t) {\n        this.Er(new __PRIVATE_DocReference(e, t));\n    }\n    dr(e, t) {\n        e.forEach((e => this.removeReference(e, t)));\n    }\n    /**\n     * Clears all references with a given ID. Calls removeRef() for each key\n     * removed.\n     */    Ar(e) {\n        const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1), i = [];\n        return this.Pr.forEachInRange([ n, r ], (e => {\n            this.Er(e), i.push(e.key);\n        })), i;\n    }\n    Rr() {\n        this.lr.forEach((e => this.Er(e)));\n    }\n    Er(e) {\n        this.lr = this.lr.delete(e), this.Pr = this.Pr.delete(e);\n    }\n    Vr(e) {\n        const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1);\n        let i = __PRIVATE_documentKeySet();\n        return this.Pr.forEachInRange([ n, r ], (e => {\n            i = i.add(e.key);\n        })), i;\n    }\n    containsKey(e) {\n        const t = new __PRIVATE_DocReference(e, 0), n = this.lr.firstAfterOrEqual(t);\n        return null !== n && e.isEqual(n.key);\n    }\n}\n\nclass __PRIVATE_DocReference {\n    constructor(e, t) {\n        this.key = e, this.mr = t;\n    }\n    /** Compare by key then by ID */    static hr(e, t) {\n        return DocumentKey.comparator(e.key, t.key) || __PRIVATE_primitiveComparator(e.mr, t.mr);\n    }\n    /** Compare by ID then by key */    static Ir(e, t) {\n        return __PRIVATE_primitiveComparator(e.mr, t.mr) || DocumentKey.comparator(e.key, t.key);\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_MemoryMutationQueue {\n    constructor(e, t) {\n        this.indexManager = e, this.referenceDelegate = t, \n        /**\n         * The set of all mutations that have been sent but not yet been applied to\n         * the backend.\n         */\n        this.mutationQueue = [], \n        /** Next value to use when assigning sequential IDs to each mutation batch. */\n        this.gr = 1, \n        /** An ordered mapping between documents and the mutations batch IDs. */\n        this.pr = new SortedSet(__PRIVATE_DocReference.hr);\n    }\n    checkEmpty(e) {\n        return PersistencePromise.resolve(0 === this.mutationQueue.length);\n    }\n    addMutationBatch(e, t, n, r) {\n        const i = this.gr;\n        this.gr++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];\n        const s = new MutationBatch(i, t, n, r);\n        this.mutationQueue.push(s);\n        // Track references by document key and index collection parents.\n        for (const t of r) this.pr = this.pr.add(new __PRIVATE_DocReference(t.key, i)), \n        this.indexManager.addToCollectionParentIndex(e, t.key.path.popLast());\n        return PersistencePromise.resolve(s);\n    }\n    lookupMutationBatch(e, t) {\n        return PersistencePromise.resolve(this.yr(t));\n    }\n    getNextMutationBatchAfterBatchId(e, t) {\n        const n = t + 1, r = this.wr(n), i = r < 0 ? 0 : r;\n        // The requested batchId may still be out of range so normalize it to the\n        // start of the queue.\n                return PersistencePromise.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);\n    }\n    getHighestUnacknowledgedBatchId() {\n        return PersistencePromise.resolve(0 === this.mutationQueue.length ? -1 : this.gr - 1);\n    }\n    getAllMutationBatches(e) {\n        return PersistencePromise.resolve(this.mutationQueue.slice());\n    }\n    getAllMutationBatchesAffectingDocumentKey(e, t) {\n        const n = new __PRIVATE_DocReference(t, 0), r = new __PRIVATE_DocReference(t, Number.POSITIVE_INFINITY), i = [];\n        return this.pr.forEachInRange([ n, r ], (e => {\n            const t = this.yr(e.mr);\n            i.push(t);\n        })), PersistencePromise.resolve(i);\n    }\n    getAllMutationBatchesAffectingDocumentKeys(e, t) {\n        let n = new SortedSet(__PRIVATE_primitiveComparator);\n        return t.forEach((e => {\n            const t = new __PRIVATE_DocReference(e, 0), r = new __PRIVATE_DocReference(e, Number.POSITIVE_INFINITY);\n            this.pr.forEachInRange([ t, r ], (e => {\n                n = n.add(e.mr);\n            }));\n        })), PersistencePromise.resolve(this.Sr(n));\n    }\n    getAllMutationBatchesAffectingQuery(e, t) {\n        // Use the query path as a prefix for testing if a document matches the\n        // query.\n        const n = t.path, r = n.length + 1;\n        // Construct a document reference for actually scanning the index. Unlike\n        // the prefix the document key in this reference must have an even number of\n        // segments. The empty segment can be used a suffix of the query path\n        // because it precedes all other segments in an ordered traversal.\n        let i = n;\n        DocumentKey.isDocumentKey(i) || (i = i.child(\"\"));\n        const s = new __PRIVATE_DocReference(new DocumentKey(i), 0);\n        // Find unique batchIDs referenced by all documents potentially matching the\n        // query.\n                let o = new SortedSet(__PRIVATE_primitiveComparator);\n        return this.pr.forEachWhile((e => {\n            const t = e.key.path;\n            return !!n.isPrefixOf(t) && (\n            // Rows with document keys more than one segment longer than the query\n            // path can't be matches. For example, a query on 'rooms' can't match\n            // the document /rooms/abc/messages/xyx.\n            // TODO(mcg): we'll need a different scanner when we implement\n            // ancestor queries.\n            t.length === r && (o = o.add(e.mr)), !0);\n        }), s), PersistencePromise.resolve(this.Sr(o));\n    }\n    Sr(e) {\n        // Construct an array of matching batches, sorted by batchID to ensure that\n        // multiple mutations affecting the same document key are applied in order.\n        const t = [];\n        return e.forEach((e => {\n            const n = this.yr(e);\n            null !== n && t.push(n);\n        })), t;\n    }\n    removeMutationBatch(e, t) {\n        __PRIVATE_hardAssert(0 === this.br(t.batchId, \"removed\")), this.mutationQueue.shift();\n        let n = this.pr;\n        return PersistencePromise.forEach(t.mutations, (r => {\n            const i = new __PRIVATE_DocReference(r.key, t.batchId);\n            return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(e, r.key);\n        })).next((() => {\n            this.pr = n;\n        }));\n    }\n    Cn(e) {\n        // No-op since the memory mutation queue does not maintain a separate cache.\n    }\n    containsKey(e, t) {\n        const n = new __PRIVATE_DocReference(t, 0), r = this.pr.firstAfterOrEqual(n);\n        return PersistencePromise.resolve(t.isEqual(r && r.key));\n    }\n    performConsistencyCheck(e) {\n        return this.mutationQueue.length, PersistencePromise.resolve();\n    }\n    /**\n     * Finds the index of the given batchId in the mutation queue and asserts that\n     * the resulting index is within the bounds of the queue.\n     *\n     * @param batchId - The batchId to search for\n     * @param action - A description of what the caller is doing, phrased in passive\n     * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n     */    br(e, t) {\n        return this.wr(e);\n    }\n    /**\n     * Finds the index of the given batchId in the mutation queue. This operation\n     * is O(1).\n     *\n     * @returns The computed index of the batch with the given batchId, based on\n     * the state of the queue. Note this index can be negative if the requested\n     * batchId has already been remvoed from the queue or past the end of the\n     * queue if the batchId is larger than the last added batch.\n     */    wr(e) {\n        if (0 === this.mutationQueue.length) \n        // As an index this is past the end of the queue\n        return 0;\n        // Examine the front of the queue to figure out the difference between the\n        // batchId and indexes in the array. Note that since the queue is ordered\n        // by batchId, if the first batch has a larger batchId then the requested\n        // batchId doesn't exist in the queue.\n                return e - this.mutationQueue[0].batchId;\n    }\n    /**\n     * A version of lookupMutationBatch that doesn't return a promise, this makes\n     * other functions that uses this code easier to read and more efficent.\n     */    yr(e) {\n        const t = this.wr(e);\n        if (t < 0 || t >= this.mutationQueue.length) return null;\n        return this.mutationQueue[t];\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass __PRIVATE_MemoryRemoteDocumentCacheImpl {\n    /**\n     * @param sizer - Used to assess the size of a document. For eager GC, this is\n     * expected to just return 0 to avoid unnecessarily doing the work of\n     * calculating the size.\n     */\n    constructor(e) {\n        this.Dr = e, \n        /** Underlying cache of documents and their read times. */\n        this.docs = function __PRIVATE_documentEntryMap() {\n            return new SortedMap(DocumentKey.comparator);\n        }(), \n        /** Size of all cached documents. */\n        this.size = 0;\n    }\n    setIndexManager(e) {\n        this.indexManager = e;\n    }\n    /**\n     * Adds the supplied entry to the cache and updates the cache size as appropriate.\n     *\n     * All calls of `addEntry`  are required to go through the RemoteDocumentChangeBuffer\n     * returned by `newChangeBuffer()`.\n     */    addEntry(e, t) {\n        const n = t.key, r = this.docs.get(n), i = r ? r.size : 0, s = this.Dr(t);\n        return this.docs = this.docs.insert(n, {\n            document: t.mutableCopy(),\n            size: s\n        }), this.size += s - i, this.indexManager.addToCollectionParentIndex(e, n.path.popLast());\n    }\n    /**\n     * Removes the specified entry from the cache and updates the cache size as appropriate.\n     *\n     * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n     * returned by `newChangeBuffer()`.\n     */    removeEntry(e) {\n        const t = this.docs.get(e);\n        t && (this.docs = this.docs.remove(e), this.size -= t.size);\n    }\n    getEntry(e, t) {\n        const n = this.docs.get(t);\n        return PersistencePromise.resolve(n ? n.document.mutableCopy() : MutableDocument.newInvalidDocument(t));\n    }\n    getEntries(e, t) {\n        let n = __PRIVATE_mutableDocumentMap();\n        return t.forEach((e => {\n            const t = this.docs.get(e);\n            n = n.insert(e, t ? t.document.mutableCopy() : MutableDocument.newInvalidDocument(e));\n        })), PersistencePromise.resolve(n);\n    }\n    getDocumentsMatchingQuery(e, t, n, r) {\n        let i = __PRIVATE_mutableDocumentMap();\n        // Documents are ordered by key, so we can use a prefix scan to narrow down\n        // the documents we need to match the query against.\n                const s = t.path, o = new DocumentKey(s.child(\"\")), _ = this.docs.getIteratorFrom(o);\n        for (;_.hasNext(); ) {\n            const {key: e, value: {document: o}} = _.getNext();\n            if (!s.isPrefixOf(e.path)) break;\n            e.path.length > s.length + 1 || (__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(o), n) <= 0 || (r.has(o.key) || __PRIVATE_queryMatches(t, o)) && (i = i.insert(o.key, o.mutableCopy())));\n        }\n        return PersistencePromise.resolve(i);\n    }\n    getAllFromCollectionGroup(e, t, n, r) {\n        // This method should only be called from the IndexBackfiller if persistence\n        // is enabled.\n        fail();\n    }\n    vr(e, t) {\n        return PersistencePromise.forEach(this.docs, (e => t(e)));\n    }\n    newChangeBuffer(e) {\n        // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n        // a separate changelog and does not need special handling for removals.\n        return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this);\n    }\n    getSize(e) {\n        return PersistencePromise.resolve(this.size);\n    }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n    constructor(e) {\n        super(), this.sr = e;\n    }\n    applyChanges(e) {\n        const t = [];\n        return this.changes.forEach(((n, r) => {\n            r.isValidDocument() ? t.push(this.sr.addEntry(e, r)) : this.sr.removeEntry(n);\n        })), PersistencePromise.waitFor(t);\n    }\n    getFromCache(e, t) {\n        return this.sr.getEntry(e, t);\n    }\n    getAllFromCache(e, t) {\n        return this.sr.getEntries(e, t);\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_MemoryTargetCache {\n    constructor(e) {\n        this.persistence = e, \n        /**\n         * Maps a target to the data about that target\n         */\n        this.Cr = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), \n        /** The last received snapshot version. */\n        this.lastRemoteSnapshotVersion = SnapshotVersion.min(), \n        /** The highest numbered target ID encountered. */\n        this.highestTargetId = 0, \n        /** The highest sequence number encountered. */\n        this.Fr = 0, \n        /**\n         * A ordered bidirectional mapping between documents and the remote target\n         * IDs.\n         */\n        this.Mr = new __PRIVATE_ReferenceSet, this.targetCount = 0, this.Or = __PRIVATE_TargetIdGenerator.xn();\n    }\n    forEachTarget(e, t) {\n        return this.Cr.forEach(((e, n) => t(n))), PersistencePromise.resolve();\n    }\n    getLastRemoteSnapshotVersion(e) {\n        return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n    }\n    getHighestSequenceNumber(e) {\n        return PersistencePromise.resolve(this.Fr);\n    }\n    allocateTargetId(e) {\n        return this.highestTargetId = this.Or.next(), PersistencePromise.resolve(this.highestTargetId);\n    }\n    setTargetsMetadata(e, t, n) {\n        return n && (this.lastRemoteSnapshotVersion = n), t > this.Fr && (this.Fr = t), \n        PersistencePromise.resolve();\n    }\n    Ln(e) {\n        this.Cr.set(e.target, e);\n        const t = e.targetId;\n        t > this.highestTargetId && (this.Or = new __PRIVATE_TargetIdGenerator(t), this.highestTargetId = t), \n        e.sequenceNumber > this.Fr && (this.Fr = e.sequenceNumber);\n    }\n    addTargetData(e, t) {\n        return this.Ln(t), this.targetCount += 1, PersistencePromise.resolve();\n    }\n    updateTargetData(e, t) {\n        return this.Ln(t), PersistencePromise.resolve();\n    }\n    removeTargetData(e, t) {\n        return this.Cr.delete(t.target), this.Mr.Ar(t.targetId), this.targetCount -= 1, \n        PersistencePromise.resolve();\n    }\n    removeTargets(e, t, n) {\n        let r = 0;\n        const i = [];\n        return this.Cr.forEach(((s, o) => {\n            o.sequenceNumber <= t && null === n.get(o.targetId) && (this.Cr.delete(s), i.push(this.removeMatchingKeysForTargetId(e, o.targetId)), \n            r++);\n        })), PersistencePromise.waitFor(i).next((() => r));\n    }\n    getTargetCount(e) {\n        return PersistencePromise.resolve(this.targetCount);\n    }\n    getTargetData(e, t) {\n        const n = this.Cr.get(t) || null;\n        return PersistencePromise.resolve(n);\n    }\n    addMatchingKeys(e, t, n) {\n        return this.Mr.Tr(t, n), PersistencePromise.resolve();\n    }\n    removeMatchingKeys(e, t, n) {\n        this.Mr.dr(t, n);\n        const r = this.persistence.referenceDelegate, i = [];\n        return r && t.forEach((t => {\n            i.push(r.markPotentiallyOrphaned(e, t));\n        })), PersistencePromise.waitFor(i);\n    }\n    removeMatchingKeysForTargetId(e, t) {\n        return this.Mr.Ar(t), PersistencePromise.resolve();\n    }\n    getMatchingKeysForTargetId(e, t) {\n        const n = this.Mr.Vr(t);\n        return PersistencePromise.resolve(n);\n    }\n    containsKey(e, t) {\n        return PersistencePromise.resolve(this.Mr.containsKey(t));\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nclass __PRIVATE_MemoryPersistence {\n    /**\n     * The constructor accepts a factory for creating a reference delegate. This\n     * allows both the delegate and this instance to have strong references to\n     * each other without having nullable fields that would then need to be\n     * checked or asserted on every access.\n     */\n    constructor(e, t) {\n        this.Nr = {}, this.overlays = {}, this.Br = new __PRIVATE_ListenSequence(0), this.Lr = !1, \n        this.Lr = !0, this.referenceDelegate = e(this), this.kr = new __PRIVATE_MemoryTargetCache(this);\n        this.indexManager = new __PRIVATE_MemoryIndexManager, this.remoteDocumentCache = function __PRIVATE_newMemoryRemoteDocumentCache(e) {\n            return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e);\n        }((e => this.referenceDelegate.qr(e))), this.serializer = new __PRIVATE_LocalSerializer(t), \n        this.Qr = new __PRIVATE_MemoryBundleCache(this.serializer);\n    }\n    start() {\n        return Promise.resolve();\n    }\n    shutdown() {\n        // No durable state to ensure is closed on shutdown.\n        return this.Lr = !1, Promise.resolve();\n    }\n    get started() {\n        return this.Lr;\n    }\n    setDatabaseDeletedListener() {\n        // No op.\n    }\n    setNetworkEnabled() {\n        // No op.\n    }\n    getIndexManager(e) {\n        // We do not currently support indices for memory persistence, so we can\n        // return the same shared instance of the memory index manager.\n        return this.indexManager;\n    }\n    getDocumentOverlayCache(e) {\n        let t = this.overlays[e.toKey()];\n        return t || (t = new __PRIVATE_MemoryDocumentOverlayCache, this.overlays[e.toKey()] = t), \n        t;\n    }\n    getMutationQueue(e, t) {\n        let n = this.Nr[e.toKey()];\n        return n || (n = new __PRIVATE_MemoryMutationQueue(t, this.referenceDelegate), this.Nr[e.toKey()] = n), \n        n;\n    }\n    getTargetCache() {\n        return this.kr;\n    }\n    getRemoteDocumentCache() {\n        return this.remoteDocumentCache;\n    }\n    getBundleCache() {\n        return this.Qr;\n    }\n    runTransaction(e, t, n) {\n        __PRIVATE_logDebug(\"MemoryPersistence\", \"Starting transaction:\", e);\n        const r = new __PRIVATE_MemoryTransaction(this.Br.next());\n        return this.referenceDelegate.Kr(), n(r).next((e => this.referenceDelegate.$r(r).next((() => e)))).toPromise().then((e => (r.raiseOnCommittedEvent(), \n        e)));\n    }\n    Ur(e, t) {\n        return PersistencePromise.or(Object.values(this.Nr).map((n => () => n.containsKey(e, t))));\n    }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */ class __PRIVATE_MemoryTransaction extends PersistenceTransaction {\n    constructor(e) {\n        super(), this.currentSequenceNumber = e;\n    }\n}\n\nclass __PRIVATE_MemoryEagerDelegate {\n    constructor(e) {\n        this.persistence = e, \n        /** Tracks all documents that are active in Query views. */\n        this.Wr = new __PRIVATE_ReferenceSet, \n        /** The list of documents that are potentially GCed after each transaction. */\n        this.Gr = null;\n    }\n    static zr(e) {\n        return new __PRIVATE_MemoryEagerDelegate(e);\n    }\n    get jr() {\n        if (this.Gr) return this.Gr;\n        throw fail();\n    }\n    addReference(e, t, n) {\n        return this.Wr.addReference(n, t), this.jr.delete(n.toString()), PersistencePromise.resolve();\n    }\n    removeReference(e, t, n) {\n        return this.Wr.removeReference(n, t), this.jr.add(n.toString()), PersistencePromise.resolve();\n    }\n    markPotentiallyOrphaned(e, t) {\n        return this.jr.add(t.toString()), PersistencePromise.resolve();\n    }\n    removeTarget(e, t) {\n        this.Wr.Ar(t.targetId).forEach((e => this.jr.add(e.toString())));\n        const n = this.persistence.getTargetCache();\n        return n.getMatchingKeysForTargetId(e, t.targetId).next((e => {\n            e.forEach((e => this.jr.add(e.toString())));\n        })).next((() => n.removeTargetData(e, t)));\n    }\n    Kr() {\n        this.Gr = new Set;\n    }\n    $r(e) {\n        // Remove newly orphaned documents.\n        const t = this.persistence.getRemoteDocumentCache().newChangeBuffer();\n        return PersistencePromise.forEach(this.jr, (n => {\n            const r = DocumentKey.fromPath(n);\n            return this.Hr(e, r).next((e => {\n                e || t.removeEntry(r, SnapshotVersion.min());\n            }));\n        })).next((() => (this.Gr = null, t.apply(e))));\n    }\n    updateLimboDocument(e, t) {\n        return this.Hr(e, t).next((e => {\n            e ? this.jr.delete(t.toString()) : this.jr.add(t.toString());\n        }));\n    }\n    qr(e) {\n        // For eager GC, we don't care about the document size, there are no size thresholds.\n        return 0;\n    }\n    Hr(e, t) {\n        return PersistencePromise.or([ () => PersistencePromise.resolve(this.Wr.containsKey(t)), () => this.persistence.getTargetCache().containsKey(e, t), () => this.persistence.Ur(e, t) ]);\n    }\n}\n\nclass __PRIVATE_MemoryLruDelegate {\n    constructor(e, t) {\n        this.persistence = e, this.Jr = new ObjectMap((e => __PRIVATE_encodeResourcePath(e.path)), ((e, t) => e.isEqual(t))), \n        this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);\n    }\n    static zr(e, t) {\n        return new __PRIVATE_MemoryLruDelegate(e, t);\n    }\n    // No-ops, present so memory persistence doesn't have to care which delegate\n    // it has.\n    Kr() {}\n    $r(e) {\n        return PersistencePromise.resolve();\n    }\n    forEachTarget(e, t) {\n        return this.persistence.getTargetCache().forEachTarget(e, t);\n    }\n    zn(e) {\n        const t = this.Jn(e);\n        return this.persistence.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t))));\n    }\n    Jn(e) {\n        let t = 0;\n        return this.jn(e, (e => {\n            t++;\n        })).next((() => t));\n    }\n    jn(e, t) {\n        return PersistencePromise.forEach(this.Jr, ((n, r) => this.Zn(e, n, r).next((e => e ? PersistencePromise.resolve() : t(r)))));\n    }\n    removeTargets(e, t, n) {\n        return this.persistence.getTargetCache().removeTargets(e, t, n);\n    }\n    removeOrphanedDocuments(e, t) {\n        let n = 0;\n        const r = this.persistence.getRemoteDocumentCache(), i = r.newChangeBuffer();\n        return r.vr(e, (r => this.Zn(e, r, t).next((e => {\n            e || (n++, i.removeEntry(r, SnapshotVersion.min()));\n        })))).next((() => i.apply(e))).next((() => n));\n    }\n    markPotentiallyOrphaned(e, t) {\n        return this.Jr.set(t, e.currentSequenceNumber), PersistencePromise.resolve();\n    }\n    removeTarget(e, t) {\n        const n = t.withSequenceNumber(e.currentSequenceNumber);\n        return this.persistence.getTargetCache().updateTargetData(e, n);\n    }\n    addReference(e, t, n) {\n        return this.Jr.set(n, e.currentSequenceNumber), PersistencePromise.resolve();\n    }\n    removeReference(e, t, n) {\n        return this.Jr.set(n, e.currentSequenceNumber), PersistencePromise.resolve();\n    }\n    updateLimboDocument(e, t) {\n        return this.Jr.set(t, e.currentSequenceNumber), PersistencePromise.resolve();\n    }\n    qr(e) {\n        let t = e.key.toString().length;\n        return e.isFoundDocument() && (t += __PRIVATE_estimateByteSize(e.data.value)), t;\n    }\n    Zn(e, t, n) {\n        return PersistencePromise.or([ () => this.persistence.Ur(e, t), () => this.persistence.getTargetCache().containsKey(e, t), () => {\n            const e = this.Jr.get(t);\n            return PersistencePromise.resolve(void 0 !== e && e > n);\n        } ]);\n    }\n    getCacheSize(e) {\n        return this.persistence.getRemoteDocumentCache().getSize(e);\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Performs database creation and schema upgrades. */ class __PRIVATE_SchemaConverter {\n    constructor(e) {\n        this.serializer = e;\n    }\n    /**\n     * Performs database creation and schema upgrades.\n     *\n     * Note that in production, this method is only ever used to upgrade the schema\n     * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n     * and local feature development.\n     */    B(e, t, n, r) {\n        const i = new __PRIVATE_SimpleDbTransaction(\"createOrUpgrade\", t);\n        n < 1 && r >= 1 && (!function __PRIVATE_createPrimaryClientStore(e) {\n            e.createObjectStore(\"owner\");\n        }(e), function __PRIVATE_createMutationQueue(e) {\n            e.createObjectStore(\"mutationQueues\", {\n                keyPath: \"userId\"\n            });\n            e.createObjectStore(\"mutations\", {\n                keyPath: \"batchId\",\n                autoIncrement: !0\n            }).createIndex(\"userMutationsIndex\", x, {\n                unique: !0\n            }), e.createObjectStore(\"documentMutations\");\n        }\n        /**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */ (e), __PRIVATE_createQueryCache(e), function __PRIVATE_createLegacyRemoteDocumentCache(e) {\n            e.createObjectStore(\"remoteDocuments\");\n        }(e));\n        // Migration 2 to populate the targetGlobal object no longer needed since\n        // migration 3 unconditionally clears it.\n                let s = PersistencePromise.resolve();\n        return n < 3 && r >= 3 && (\n        // Brand new clients don't need to drop and recreate--only clients that\n        // potentially have corrupt data.\n        0 !== n && (!function __PRIVATE_dropQueryCache(e) {\n            e.deleteObjectStore(\"targetDocuments\"), e.deleteObjectStore(\"targets\"), e.deleteObjectStore(\"targetGlobal\");\n        }(e), __PRIVATE_createQueryCache(e)), s = s.next((() => \n        /**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\n        function __PRIVATE_writeEmptyTargetGlobalEntry(e) {\n            const t = e.store(\"targetGlobal\"), n = {\n                highestTargetId: 0,\n                highestListenSequenceNumber: 0,\n                lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n                targetCount: 0\n            };\n            return t.put(\"targetGlobalKey\", n);\n        }(i)))), n < 4 && r >= 4 && (0 !== n && (\n        // Schema version 3 uses auto-generated keys to generate globally unique\n        // mutation batch IDs (this was previously ensured internally by the\n        // client). To migrate to the new schema, we have to read all mutations\n        // and write them back out. We preserve the existing batch IDs to guarantee\n        // consistency with other object stores. Any further mutation batch IDs will\n        // be auto-generated.\n        s = s.next((() => function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e, t) {\n            return t.store(\"mutations\").G().next((n => {\n                e.deleteObjectStore(\"mutations\");\n                e.createObjectStore(\"mutations\", {\n                    keyPath: \"batchId\",\n                    autoIncrement: !0\n                }).createIndex(\"userMutationsIndex\", x, {\n                    unique: !0\n                });\n                const r = t.store(\"mutations\"), i = n.map((e => r.put(e)));\n                return PersistencePromise.waitFor(i);\n            }));\n        }(e, i)))), s = s.next((() => {\n            !function __PRIVATE_createClientMetadataStore(e) {\n                e.createObjectStore(\"clientMetadata\", {\n                    keyPath: \"clientId\"\n                });\n            }(e);\n        }))), n < 5 && r >= 5 && (s = s.next((() => this.Yr(i)))), n < 6 && r >= 6 && (s = s.next((() => (function __PRIVATE_createDocumentGlobalStore(e) {\n            e.createObjectStore(\"remoteDocumentGlobal\");\n        }(e), this.Zr(i))))), n < 7 && r >= 7 && (s = s.next((() => this.Xr(i)))), n < 8 && r >= 8 && (s = s.next((() => this.ei(e, i)))), \n        n < 9 && r >= 9 && (s = s.next((() => {\n            // Multi-Tab used to manage its own changelog, but this has been moved\n            // to the DbRemoteDocument object store itself. Since the previous change\n            // log only contained transient data, we can drop its object store.\n            !function __PRIVATE_dropRemoteDocumentChangesStore(e) {\n                e.objectStoreNames.contains(\"remoteDocumentChanges\") && e.deleteObjectStore(\"remoteDocumentChanges\");\n            }(e);\n            // Note: Schema version 9 used to create a read time index for the\n            // RemoteDocumentCache. This is now done with schema version 13.\n                }))), n < 10 && r >= 10 && (s = s.next((() => this.ti(i)))), n < 11 && r >= 11 && (s = s.next((() => {\n            !function __PRIVATE_createBundlesStore(e) {\n                e.createObjectStore(\"bundles\", {\n                    keyPath: \"bundleId\"\n                });\n            }(e), function __PRIVATE_createNamedQueriesStore(e) {\n                e.createObjectStore(\"namedQueries\", {\n                    keyPath: \"name\"\n                });\n            }(e);\n        }))), n < 12 && r >= 12 && (s = s.next((() => {\n            !function __PRIVATE_createDocumentOverlayStore(e) {\n                const t = e.createObjectStore(\"documentOverlays\", {\n                    keyPath: z\n                });\n                t.createIndex(\"collectionPathOverlayIndex\", j, {\n                    unique: !1\n                }), t.createIndex(\"collectionGroupOverlayIndex\", H, {\n                    unique: !1\n                });\n            }(e);\n        }))), n < 13 && r >= 13 && (s = s.next((() => function __PRIVATE_createRemoteDocumentCache(e) {\n            const t = e.createObjectStore(\"remoteDocumentsV14\", {\n                keyPath: N\n            });\n            t.createIndex(\"documentKeyIndex\", B), t.createIndex(\"collectionGroupIndex\", L);\n        }(e))).next((() => this.ni(e, i))).next((() => e.deleteObjectStore(\"remoteDocuments\")))), \n        n < 14 && r >= 14 && (s = s.next((() => this.ri(e, i)))), n < 15 && r >= 15 && (s = s.next((() => function __PRIVATE_createFieldIndex(e) {\n            e.createObjectStore(\"indexConfiguration\", {\n                keyPath: \"indexId\",\n                autoIncrement: !0\n            }).createIndex(\"collectionGroupIndex\", \"collectionGroup\", {\n                unique: !1\n            });\n            e.createObjectStore(\"indexState\", {\n                keyPath: $\n            }).createIndex(\"sequenceNumberIndex\", U, {\n                unique: !1\n            });\n            e.createObjectStore(\"indexEntries\", {\n                keyPath: W\n            }).createIndex(\"documentKeyIndex\", G, {\n                unique: !1\n            });\n        }(e)))), s;\n    }\n    Zr(e) {\n        let t = 0;\n        return e.store(\"remoteDocuments\").Z(((e, n) => {\n            t += __PRIVATE_dbDocumentSize(n);\n        })).next((() => {\n            const n = {\n                byteSize: t\n            };\n            return e.store(\"remoteDocumentGlobal\").put(\"remoteDocumentGlobalKey\", n);\n        }));\n    }\n    Yr(e) {\n        const t = e.store(\"mutationQueues\"), n = e.store(\"mutations\");\n        return t.G().next((t => PersistencePromise.forEach(t, (t => {\n            const r = IDBKeyRange.bound([ t.userId, -1 ], [ t.userId, t.lastAcknowledgedBatchId ]);\n            return n.G(\"userMutationsIndex\", r).next((n => PersistencePromise.forEach(n, (n => {\n                __PRIVATE_hardAssert(n.userId === t.userId);\n                const r = __PRIVATE_fromDbMutationBatch(this.serializer, n);\n                return removeMutationBatch(e, t.userId, r).next((() => {}));\n            }))));\n        }))));\n    }\n    /**\n     * Ensures that every document in the remote document cache has a corresponding sentinel row\n     * with a sequence number. Missing rows are given the most recently used sequence number.\n     */    Xr(e) {\n        const t = e.store(\"targetDocuments\"), n = e.store(\"remoteDocuments\");\n        return e.store(\"targetGlobal\").get(\"targetGlobalKey\").next((e => {\n            const r = [];\n            return n.Z(((n, i) => {\n                const s = new ResourcePath(n), o = function __PRIVATE_sentinelKey(e) {\n                    return [ 0, __PRIVATE_encodeResourcePath(e) ];\n                }(s);\n                r.push(t.get(o).next((n => n ? PersistencePromise.resolve() : (n => t.put({\n                    targetId: 0,\n                    path: __PRIVATE_encodeResourcePath(n),\n                    sequenceNumber: e.highestListenSequenceNumber\n                }))(s))));\n            })).next((() => PersistencePromise.waitFor(r)));\n        }));\n    }\n    ei(e, t) {\n        // Create the index.\n        e.createObjectStore(\"collectionParents\", {\n            keyPath: K\n        });\n        const n = t.store(\"collectionParents\"), r = new __PRIVATE_MemoryCollectionParentIndex, addEntry = e => {\n            if (r.add(e)) {\n                const t = e.lastSegment(), r = e.popLast();\n                return n.put({\n                    collectionId: t,\n                    parent: __PRIVATE_encodeResourcePath(r)\n                });\n            }\n        };\n        // Helper to add an index entry iff we haven't already written it.\n                // Index existing remote documents.\n        return t.store(\"remoteDocuments\").Z({\n            Y: !0\n        }, ((e, t) => {\n            const n = new ResourcePath(e);\n            return addEntry(n.popLast());\n        })).next((() => t.store(\"documentMutations\").Z({\n            Y: !0\n        }, (([e, t, n], r) => {\n            const i = __PRIVATE_decodeResourcePath(t);\n            return addEntry(i.popLast());\n        }))));\n    }\n    ti(e) {\n        const t = e.store(\"targets\");\n        return t.Z(((e, n) => {\n            const r = __PRIVATE_fromDbTarget(n), i = __PRIVATE_toDbTarget(this.serializer, r);\n            return t.put(i);\n        }));\n    }\n    ni(e, t) {\n        const n = t.store(\"remoteDocuments\"), r = [];\n        return n.Z(((e, n) => {\n            const i = t.store(\"remoteDocumentsV14\"), s = function __PRIVATE_extractKey(e) {\n                return e.document ? new DocumentKey(ResourcePath.fromString(e.document.name).popFirst(5)) : e.noDocument ? DocumentKey.fromSegments(e.noDocument.path) : e.unknownDocument ? DocumentKey.fromSegments(e.unknownDocument.path) : fail();\n            }\n            /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (n).path.toArray(), o = {\n                prefixPath: s.slice(0, s.length - 2),\n                collectionGroup: s[s.length - 2],\n                documentId: s[s.length - 1],\n                readTime: n.readTime || [ 0, 0 ],\n                unknownDocument: n.unknownDocument,\n                noDocument: n.noDocument,\n                document: n.document,\n                hasCommittedMutations: !!n.hasCommittedMutations\n            };\n            r.push(i.put(o));\n        })).next((() => PersistencePromise.waitFor(r)));\n    }\n    ri(e, t) {\n        const n = t.store(\"mutations\"), r = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), i = new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.zr, this.serializer.ct);\n        return n.G().next((e => {\n            const n = new Map;\n            return e.forEach((e => {\n                var t;\n                let r = null !== (t = n.get(e.userId)) && void 0 !== t ? t : __PRIVATE_documentKeySet();\n                __PRIVATE_fromDbMutationBatch(this.serializer, e).keys().forEach((e => r = r.add(e))), \n                n.set(e.userId, r);\n            })), PersistencePromise.forEach(n, ((e, n) => {\n                const s = new User(n), o = __PRIVATE_IndexedDbDocumentOverlayCache.lt(this.serializer, s), _ = i.getIndexManager(s), a = __PRIVATE_IndexedDbMutationQueue.lt(s, this.serializer, _, i.referenceDelegate);\n                return new LocalDocumentsView(r, a, o, _).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(t, __PRIVATE_ListenSequence.ae), e).next();\n            }));\n        }));\n    }\n}\n\nfunction __PRIVATE_createQueryCache(e) {\n    e.createObjectStore(\"targetDocuments\", {\n        keyPath: q\n    }).createIndex(\"documentTargetsIndex\", Q, {\n        unique: !0\n    });\n    // NOTE: This is unique only because the TargetId is the suffix.\n    e.createObjectStore(\"targets\", {\n        keyPath: \"targetId\"\n    }).createIndex(\"queryTargetsIndex\", k, {\n        unique: !0\n    }), e.createObjectStore(\"targetGlobal\");\n}\n\nconst Ae = \"Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.\";\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nclass __PRIVATE_IndexedDbPersistence {\n    constructor(\n    /**\n     * Whether to synchronize the in-memory state of multiple tabs and share\n     * access to local persistence.\n     */\n    e, t, n, r, i, s, o, _, a, \n    /**\n     * If set to true, forcefully obtains database access. Existing tabs will\n     * no longer be able to access IndexedDB.\n     */\n    u, c = 15) {\n        if (this.allowTabSynchronization = e, this.persistenceKey = t, this.clientId = n, \n        this.ii = i, this.window = s, this.document = o, this.si = a, this.oi = u, this._i = c, \n        this.Br = null, this.Lr = !1, this.isPrimary = !1, this.networkEnabled = !0, \n        /** Our window.unload handler, if registered. */\n        this.ai = null, this.inForeground = !1, \n        /** Our 'visibilitychange' listener if registered. */\n        this.ui = null, \n        /** The client metadata refresh task. */\n        this.ci = null, \n        /** The last time we garbage collected the client metadata object store. */\n        this.li = Number.NEGATIVE_INFINITY, \n        /** A listener to notify on primary state changes. */\n        this.hi = e => Promise.resolve(), !__PRIVATE_IndexedDbPersistence.v()) throw new FirestoreError(v.UNIMPLEMENTED, \"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.\");\n        this.referenceDelegate = new __PRIVATE_IndexedDbLruDelegateImpl(this, r), this.Pi = t + \"main\", \n        this.serializer = new __PRIVATE_LocalSerializer(_), this.Ii = new __PRIVATE_SimpleDb(this.Pi, this._i, new __PRIVATE_SchemaConverter(this.serializer)), \n        this.kr = new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate, this.serializer), \n        this.remoteDocumentCache = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), \n        this.Qr = new __PRIVATE_IndexedDbBundleCache, this.window && this.window.localStorage ? this.Ti = this.window.localStorage : (this.Ti = null, \n        !1 === u && __PRIVATE_logError(\"IndexedDbPersistence\", \"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.\"));\n    }\n    /**\n     * Attempt to start IndexedDb persistence.\n     *\n     * @returns Whether persistence was enabled.\n     */    start() {\n        // NOTE: This is expected to fail sometimes (in the case of another tab\n        // already having the persistence lock), so it's the first thing we should\n        // do.\n        return this.Ei().then((() => {\n            if (!this.isPrimary && !this.allowTabSynchronization) \n            // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n            // obtain the primary lease.\n            throw new FirestoreError(v.FAILED_PRECONDITION, Ae);\n            return this.di(), this.Ai(), this.Ri(), this.runTransaction(\"getHighestListenSequenceNumber\", \"readonly\", (e => this.kr.getHighestSequenceNumber(e)));\n        })).then((e => {\n            this.Br = new __PRIVATE_ListenSequence(e, this.si);\n        })).then((() => {\n            this.Lr = !0;\n        })).catch((e => (this.Ii && this.Ii.close(), Promise.reject(e))));\n    }\n    /**\n     * Registers a listener that gets called when the primary state of the\n     * instance changes. Upon registering, this listener is invoked immediately\n     * with the current primary state.\n     *\n     * PORTING NOTE: This is only used for Web multi-tab.\n     */    Vi(e) {\n        return this.hi = async t => {\n            if (this.started) return e(t);\n        }, e(this.isPrimary);\n    }\n    /**\n     * Registers a listener that gets called when the database receives a\n     * version change event indicating that it has deleted.\n     *\n     * PORTING NOTE: This is only used for Web multi-tab.\n     */    setDatabaseDeletedListener(e) {\n        this.Ii.k((async t => {\n            // Check if an attempt is made to delete IndexedDB.\n            null === t.newVersion && await e();\n        }));\n    }\n    /**\n     * Adjusts the current network state in the client's metadata, potentially\n     * affecting the primary lease.\n     *\n     * PORTING NOTE: This is only used for Web multi-tab.\n     */    setNetworkEnabled(e) {\n        this.networkEnabled !== e && (this.networkEnabled = e, \n        // Schedule a primary lease refresh for immediate execution. The eventual\n        // lease update will be propagated via `primaryStateListener`.\n        this.ii.enqueueAndForget((async () => {\n            this.started && await this.Ei();\n        })));\n    }\n    /**\n     * Updates the client metadata in IndexedDb and attempts to either obtain or\n     * extend the primary lease for the local client. Asynchronously notifies the\n     * primary state listener if the client either newly obtained or released its\n     * primary lease.\n     */    Ei() {\n        return this.runTransaction(\"updateClientMetadataAndTryBecomePrimary\", \"readwrite\", (e => __PRIVATE_clientMetadataStore(e).put({\n            clientId: this.clientId,\n            updateTimeMs: Date.now(),\n            networkEnabled: this.networkEnabled,\n            inForeground: this.inForeground\n        }).next((() => {\n            if (this.isPrimary) return this.mi(e).next((e => {\n                e || (this.isPrimary = !1, this.ii.enqueueRetryable((() => this.hi(!1))));\n            }));\n        })).next((() => this.fi(e))).next((t => this.isPrimary && !t ? this.gi(e).next((() => !1)) : !!t && this.pi(e).next((() => !0)))))).catch((e => {\n            if (__PRIVATE_isIndexedDbTransactionError(e)) \n            // Proceed with the existing state. Any subsequent access to\n            // IndexedDB will verify the lease.\n            return __PRIVATE_logDebug(\"IndexedDbPersistence\", \"Failed to extend owner lease: \", e), \n            this.isPrimary;\n            if (!this.allowTabSynchronization) throw e;\n            return __PRIVATE_logDebug(\"IndexedDbPersistence\", \"Releasing owner lease after error during lease refresh\", e), \n            /* isPrimary= */ !1;\n        })).then((e => {\n            this.isPrimary !== e && this.ii.enqueueRetryable((() => this.hi(e))), this.isPrimary = e;\n        }));\n    }\n    mi(e) {\n        return __PRIVATE_primaryClientStore(e).get(\"owner\").next((e => PersistencePromise.resolve(this.yi(e))));\n    }\n    wi(e) {\n        return __PRIVATE_clientMetadataStore(e).delete(this.clientId);\n    }\n    /**\n     * If the garbage collection threshold has passed, prunes the\n     * RemoteDocumentChanges and the ClientMetadata store based on the last update\n     * time of all clients.\n     */    async Si() {\n        if (this.isPrimary && !this.bi(this.li, 18e5)) {\n            this.li = Date.now();\n            const e = await this.runTransaction(\"maybeGarbageCollectMultiClientState\", \"readwrite-primary\", (e => {\n                const t = __PRIVATE_getStore(e, \"clientMetadata\");\n                return t.G().next((e => {\n                    const n = this.Di(e, 18e5), r = e.filter((e => -1 === n.indexOf(e)));\n                    // Delete metadata for clients that are no longer considered active.\n                    return PersistencePromise.forEach(r, (e => t.delete(e.clientId))).next((() => r));\n                }));\n            })).catch((() => []));\n            // Delete potential leftover entries that may continue to mark the\n            // inactive clients as zombied in LocalStorage.\n            // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n            // the client atomically, but we can't. So we opt to delete the IndexedDb\n            // entries first to avoid potentially reviving a zombied client.\n                        if (this.Ti) for (const t of e) this.Ti.removeItem(this.vi(t.clientId));\n        }\n    }\n    /**\n     * Schedules a recurring timer to update the client metadata and to either\n     * extend or acquire the primary lease if the client is eligible.\n     */    Ri() {\n        this.ci = this.ii.enqueueAfterDelay(\"client_metadata_refresh\" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.Ei().then((() => this.Si())).then((() => this.Ri()))));\n    }\n    /** Checks whether `client` is the local client. */    yi(e) {\n        return !!e && e.ownerId === this.clientId;\n    }\n    /**\n     * Evaluate the state of all active clients and determine whether the local\n     * client is or can act as the holder of the primary lease. Returns whether\n     * the client is eligible for the lease, but does not actually acquire it.\n     * May return 'false' even if there is no active leaseholder and another\n     * (foreground) client should become leaseholder instead.\n     */    fi(e) {\n        if (this.oi) return PersistencePromise.resolve(!0);\n        return __PRIVATE_primaryClientStore(e).get(\"owner\").next((t => {\n            // A client is eligible for the primary lease if:\n            // - its network is enabled and the client's tab is in the foreground.\n            // - its network is enabled and no other client's tab is in the\n            //   foreground.\n            // - every clients network is disabled and the client's tab is in the\n            //   foreground.\n            // - every clients network is disabled and no other client's tab is in\n            //   the foreground.\n            // - the `forceOwningTab` setting was passed in.\n            if (null !== t && this.bi(t.leaseTimestampMs, 5e3) && !this.Ci(t.ownerId)) {\n                if (this.yi(t) && this.networkEnabled) return !0;\n                if (!this.yi(t)) {\n                    if (!t.allowTabSynchronization) \n                    // Fail the `canActAsPrimary` check if the current leaseholder has\n                    // not opted into multi-tab synchronization. If this happens at\n                    // client startup, we reject the Promise returned by\n                    // `enablePersistence()` and the user can continue to use Firestore\n                    // with in-memory persistence.\n                    // If this fails during a lease refresh, we will instead block the\n                    // AsyncQueue from executing further operations. Note that this is\n                    // acceptable since mixing & matching different `synchronizeTabs`\n                    // settings is not supported.\n                    // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n                    // no longer be turned off.\n                    throw new FirestoreError(v.FAILED_PRECONDITION, Ae);\n                    return !1;\n                }\n            }\n            return !(!this.networkEnabled || !this.inForeground) || __PRIVATE_clientMetadataStore(e).G().next((e => void 0 === this.Di(e, 5e3).find((e => {\n                if (this.clientId !== e.clientId) {\n                    const t = !this.networkEnabled && e.networkEnabled, n = !this.inForeground && e.inForeground, r = this.networkEnabled === e.networkEnabled;\n                    if (t || n && r) return !0;\n                }\n                return !1;\n            }))));\n        })).next((e => (this.isPrimary !== e && __PRIVATE_logDebug(\"IndexedDbPersistence\", `Client ${e ? \"is\" : \"is not\"} eligible for a primary lease.`), \n        e)));\n    }\n    async shutdown() {\n        // The shutdown() operations are idempotent and can be called even when\n        // start() aborted (e.g. because it couldn't acquire the persistence lease).\n        this.Lr = !1, this.Fi(), this.ci && (this.ci.cancel(), this.ci = null), this.Mi(), \n        this.xi(), \n        // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n        // has obtained the primary lease.\n        await this.Ii.runTransaction(\"shutdown\", \"readwrite\", [ \"owner\", \"clientMetadata\" ], (e => {\n            const t = new __PRIVATE_IndexedDbTransaction(e, __PRIVATE_ListenSequence.ae);\n            return this.gi(t).next((() => this.wi(t)));\n        })), this.Ii.close(), \n        // Remove the entry marking the client as zombied from LocalStorage since\n        // we successfully deleted its metadata from IndexedDb.\n        this.Oi();\n    }\n    /**\n     * Returns clients that are not zombied and have an updateTime within the\n     * provided threshold.\n     */    Di(e, t) {\n        return e.filter((e => this.bi(e.updateTimeMs, t) && !this.Ci(e.clientId)));\n    }\n    /**\n     * Returns the IDs of the clients that are currently active. If multi-tab\n     * is not supported, returns an array that only contains the local client's\n     * ID.\n     *\n     * PORTING NOTE: This is only used for Web multi-tab.\n     */    Ni() {\n        return this.runTransaction(\"getActiveClients\", \"readonly\", (e => __PRIVATE_clientMetadataStore(e).G().next((e => this.Di(e, 18e5).map((e => e.clientId))))));\n    }\n    get started() {\n        return this.Lr;\n    }\n    getMutationQueue(e, t) {\n        return __PRIVATE_IndexedDbMutationQueue.lt(e, this.serializer, t, this.referenceDelegate);\n    }\n    getTargetCache() {\n        return this.kr;\n    }\n    getRemoteDocumentCache() {\n        return this.remoteDocumentCache;\n    }\n    getIndexManager(e) {\n        return new __PRIVATE_IndexedDbIndexManager(e, this.serializer.ct.databaseId);\n    }\n    getDocumentOverlayCache(e) {\n        return __PRIVATE_IndexedDbDocumentOverlayCache.lt(this.serializer, e);\n    }\n    getBundleCache() {\n        return this.Qr;\n    }\n    runTransaction(e, t, n) {\n        __PRIVATE_logDebug(\"IndexedDbPersistence\", \"Starting transaction:\", e);\n        const r = \"readonly\" === t ? \"readonly\" : \"readwrite\", i = \n        /** Returns the object stores for the provided schema. */\n        function __PRIVATE_getObjectStores(e) {\n            return 15 === e ? ee : 14 === e ? X : 13 === e ? Z : 12 === e ? Y : 11 === e ? J : void fail();\n        }(this._i);\n        let s;\n        // Do all transactions as readwrite against all object stores, since we\n        // are the only reader/writer.\n                return this.Ii.runTransaction(e, r, i, (r => (s = new __PRIVATE_IndexedDbTransaction(r, this.Br ? this.Br.next() : __PRIVATE_ListenSequence.ae), \n        \"readwrite-primary\" === t ? this.mi(s).next((e => !!e || this.fi(s))).next((t => {\n            if (!t) throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e}'.`), \n            this.isPrimary = !1, this.ii.enqueueRetryable((() => this.hi(!1))), new FirestoreError(v.FAILED_PRECONDITION, F);\n            return n(s);\n        })).next((e => this.pi(s).next((() => e)))) : this.Bi(s).next((() => n(s)))))).then((e => (s.raiseOnCommittedEvent(), \n        e)));\n    }\n    /**\n     * Verifies that the current tab is the primary leaseholder or alternatively\n     * that the leaseholder has opted into multi-tab synchronization.\n     */\n    // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n    // be turned off.\n    Bi(e) {\n        return __PRIVATE_primaryClientStore(e).get(\"owner\").next((e => {\n            if (null !== e && this.bi(e.leaseTimestampMs, 5e3) && !this.Ci(e.ownerId) && !this.yi(e) && !(this.oi || this.allowTabSynchronization && e.allowTabSynchronization)) throw new FirestoreError(v.FAILED_PRECONDITION, Ae);\n        }));\n    }\n    /**\n     * Obtains or extends the new primary lease for the local client. This\n     * method does not verify that the client is eligible for this lease.\n     */    pi(e) {\n        const t = {\n            ownerId: this.clientId,\n            allowTabSynchronization: this.allowTabSynchronization,\n            leaseTimestampMs: Date.now()\n        };\n        return __PRIVATE_primaryClientStore(e).put(\"owner\", t);\n    }\n    static v() {\n        return __PRIVATE_SimpleDb.v();\n    }\n    /** Checks the primary lease and removes it if we are the current primary. */    gi(e) {\n        const t = __PRIVATE_primaryClientStore(e);\n        return t.get(\"owner\").next((e => this.yi(e) ? (__PRIVATE_logDebug(\"IndexedDbPersistence\", \"Releasing primary lease.\"), \n        t.delete(\"owner\")) : PersistencePromise.resolve()));\n    }\n    /** Verifies that `updateTimeMs` is within `maxAgeMs`. */    bi(e, t) {\n        const n = Date.now();\n        return !(e < n - t) && (!(e > n) || (__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${n}`), \n        !1));\n    }\n    di() {\n        null !== this.document && \"function\" == typeof this.document.addEventListener && (this.ui = () => {\n            this.ii.enqueueAndForget((() => (this.inForeground = \"visible\" === this.document.visibilityState, \n            this.Ei())));\n        }, this.document.addEventListener(\"visibilitychange\", this.ui), this.inForeground = \"visible\" === this.document.visibilityState);\n    }\n    Mi() {\n        this.ui && (this.document.removeEventListener(\"visibilitychange\", this.ui), this.ui = null);\n    }\n    /**\n     * Attaches a window.unload handler that will synchronously write our\n     * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n     * by tabs trying to acquire the primary lease to determine that the lease\n     * is no longer valid even if the timestamp is recent. This is particularly\n     * important for the refresh case (so the tab correctly re-acquires the\n     * primary lease). LocalStorage is used for this rather than IndexedDb because\n     * it is a synchronous API and so can be used reliably from  an unload\n     * handler.\n     */    Ai() {\n        var e;\n        \"function\" == typeof (null === (e = this.window) || void 0 === e ? void 0 : e.addEventListener) && (this.ai = () => {\n            // Note: In theory, this should be scheduled on the AsyncQueue since it\n            // accesses internal state. We execute this code directly during shutdown\n            // to make sure it gets a chance to run.\n            this.Fi();\n            const e = /(?:Version|Mobile)\\/1[456]/;\n            isSafari() && (navigator.appVersion.match(e) || navigator.userAgent.match(e)) && \n            // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n            // trigger a bug that prevents Safari from re-opening IndexedDB during\n            // the next page load.\n            // See https://bugs.webkit.org/show_bug.cgi?id=226547\n            this.ii.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.ii.enqueueAndForget((() => this.shutdown()));\n        }, this.window.addEventListener(\"pagehide\", this.ai));\n    }\n    xi() {\n        this.ai && (this.window.removeEventListener(\"pagehide\", this.ai), this.ai = null);\n    }\n    /**\n     * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n     * Clients become zombied when their tab closes without running all of the\n     * cleanup logic in `shutdown()`.\n     */    Ci(e) {\n        var t;\n        try {\n            const n = null !== (null === (t = this.Ti) || void 0 === t ? void 0 : t.getItem(this.vi(e)));\n            return __PRIVATE_logDebug(\"IndexedDbPersistence\", `Client '${e}' ${n ? \"is\" : \"is not\"} zombied in LocalStorage`), \n            n;\n        } catch (e) {\n            // Gracefully handle if LocalStorage isn't working.\n            return __PRIVATE_logError(\"IndexedDbPersistence\", \"Failed to get zombied client id.\", e), \n            !1;\n        }\n    }\n    /**\n     * Record client as zombied (a client that had its tab closed). Zombied\n     * clients are ignored during primary tab selection.\n     */    Fi() {\n        if (this.Ti) try {\n            this.Ti.setItem(this.vi(this.clientId), String(Date.now()));\n        } catch (e) {\n            // Gracefully handle if LocalStorage isn't available / working.\n            __PRIVATE_logError(\"Failed to set zombie client id.\", e);\n        }\n    }\n    /** Removes the zombied client entry if it exists. */    Oi() {\n        if (this.Ti) try {\n            this.Ti.removeItem(this.vi(this.clientId));\n        } catch (e) {\n            // Ignore\n        }\n    }\n    vi(e) {\n        return `firestore_zombie_${this.persistenceKey}_${e}`;\n    }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */ function __PRIVATE_primaryClientStore(e) {\n    return __PRIVATE_getStore(e, \"owner\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */ function __PRIVATE_clientMetadataStore(e) {\n    return __PRIVATE_getStore(e, \"clientMetadata\");\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */ function __PRIVATE_indexedDbStoragePrefix(e, t) {\n    // Use two different prefix formats:\n    //   * firestore / persistenceKey / projectID . databaseID / ...\n    //   * firestore / persistenceKey / projectID / ...\n    // projectIDs are DNS-compatible names and cannot contain dots\n    // so there's no danger of collisions.\n    let n = e.projectId;\n    return e.isDefaultDatabase || (n += \".\" + e.database), \"firestore/\" + t + \"/\" + n + \"/\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nclass __PRIVATE_LocalViewChanges {\n    constructor(e, t, n, r) {\n        this.targetId = e, this.fromCache = t, this.Li = n, this.ki = r;\n    }\n    static qi(e, t) {\n        let n = __PRIVATE_documentKeySet(), r = __PRIVATE_documentKeySet();\n        for (const e of t.docChanges) switch (e.type) {\n          case 0 /* ChangeType.Added */ :\n            n = n.add(e.doc.key);\n            break;\n\n          case 1 /* ChangeType.Removed */ :\n            r = r.add(e.doc.key);\n // do nothing\n                }\n        return new __PRIVATE_LocalViewChanges(e, t.fromCache, n, r);\n    }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n *   matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n *   another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */ class __PRIVATE_QueryEngine {\n    constructor() {\n        this.Qi = !1;\n    }\n    /** Sets the document view to query against. */    initialize(e, t) {\n        this.Ki = e, this.indexManager = t, this.Qi = !0;\n    }\n    /** Returns all local documents matching the specified query. */    getDocumentsMatchingQuery(e, t, n, r) {\n        return this.$i(e, t).next((i => i || this.Ui(e, t, r, n))).next((n => n || this.Wi(e, t)));\n    }\n    /**\n     * Performs an indexed query that evaluates the query based on a collection's\n     * persisted index values. Returns `null` if an index is not available.\n     */    $i(e, t) {\n        if (__PRIVATE_queryMatchesAllDocuments(t)) \n        // Queries that match all documents don't benefit from using\n        // key-based lookups. It is more efficient to scan all documents in a\n        // collection, rather than to perform individual lookups.\n        return PersistencePromise.resolve(null);\n        let n = __PRIVATE_queryToTarget(t);\n        return this.indexManager.getIndexType(e, n).next((r => 0 /* IndexType.NONE */ === r ? null : (null !== t.limit && 1 /* IndexType.PARTIAL */ === r && (\n        // We cannot apply a limit for targets that are served using a partial\n        // index. If a partial index will be used to serve the target, the\n        // query may return a superset of documents that match the target\n        // (e.g. if the index doesn't include all the target's filters), or\n        // may return the correct set of documents in the wrong order (e.g. if\n        // the index doesn't include a segment for one of the orderBys).\n        // Therefore, a limit should not be applied in such cases.\n        t = __PRIVATE_queryWithLimit(t, null, \"F\" /* LimitType.First */), n = __PRIVATE_queryToTarget(t)), \n        this.indexManager.getDocumentsMatchingTarget(e, n).next((r => {\n            const i = __PRIVATE_documentKeySet(...r);\n            return this.Ki.getDocuments(e, i).next((r => this.indexManager.getMinOffset(e, n).next((n => {\n                const s = this.Gi(t, r);\n                return this.zi(t, s, i, n.readTime) ? this.$i(e, __PRIVATE_queryWithLimit(t, null, \"F\" /* LimitType.First */)) : this.ji(e, s, t, n);\n            }))));\n        })))));\n    }\n    /**\n     * Performs a query based on the target's persisted query mapping. Returns\n     * `null` if the mapping is not available or cannot be used.\n     */    Ui(e, t, n, r) {\n        return __PRIVATE_queryMatchesAllDocuments(t) || r.isEqual(SnapshotVersion.min()) ? this.Wi(e, t) : this.Ki.getDocuments(e, n).next((i => {\n            const s = this.Gi(t, i);\n            return this.zi(t, s, n, r) ? this.Wi(e, t) : (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"Re-using previous result from %s to execute query: %s\", r.toString(), __PRIVATE_stringifyQuery(t)), \n            this.ji(e, s, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, -1)));\n        }));\n        // Queries that have never seen a snapshot without limbo free documents\n        // should also be run as a full collection scan.\n        }\n    /** Applies the query filter and sorting to the provided documents.  */    Gi(e, t) {\n        // Sort the documents and re-apply the query filter since previously\n        // matching documents do not necessarily still match the query.\n        let n = new SortedSet(__PRIVATE_newQueryComparator(e));\n        return t.forEach(((t, r) => {\n            __PRIVATE_queryMatches(e, r) && (n = n.add(r));\n        })), n;\n    }\n    /**\n     * Determines if a limit query needs to be refilled from cache, making it\n     * ineligible for index-free execution.\n     *\n     * @param query - The query.\n     * @param sortedPreviousResults - The documents that matched the query when it\n     * was last synchronized, sorted by the query's comparator.\n     * @param remoteKeys - The document keys that matched the query at the last\n     * snapshot.\n     * @param limboFreeSnapshotVersion - The version of the snapshot when the\n     * query was last synchronized.\n     */    zi(e, t, n, r) {\n        if (null === e.limit) \n        // Queries without limits do not need to be refilled.\n        return !1;\n        if (n.size !== t.size) \n        // The query needs to be refilled if a previously matching document no\n        // longer matches.\n        return !0;\n        // Limit queries are not eligible for index-free query execution if there is\n        // a potential that an older document from cache now sorts before a document\n        // that was previously part of the limit. This, however, can only happen if\n        // the document at the edge of the limit goes out of limit.\n        // If a document that is not the limit boundary sorts differently,\n        // the boundary of the limit itself did not change and documents from cache\n        // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n        // any modifications that don't affect the last document.\n                const i = \"F\" /* LimitType.First */ === e.limitType ? t.last() : t.first();\n        return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0);\n    }\n    Wi(e, t) {\n        return __PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug(\"QueryEngine\", \"Using full collection scan to execute query:\", __PRIVATE_stringifyQuery(t)), \n        this.Ki.getDocumentsMatchingQuery(e, t, IndexOffset.min());\n    }\n    /**\n     * Combines the results from an indexed execution with the remaining documents\n     * that have not yet been indexed.\n     */    ji(e, t, n, r) {\n        // Retrieve all results for documents that were updated since the offset.\n        return this.Ki.getDocumentsMatchingQuery(e, n, r).next((e => (\n        // Merge with existing results\n        t.forEach((t => {\n            e = e.insert(t.key, t);\n        })), e)));\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass __PRIVATE_LocalStoreImpl {\n    constructor(\n    /** Manages our in-memory or durable persistence. */\n    e, t, n, r) {\n        this.persistence = e, this.Hi = t, this.serializer = r, \n        /**\n         * Maps a targetID to data about its target.\n         *\n         * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n         * of `applyRemoteEvent()` idempotent.\n         */\n        this.Ji = new SortedMap(__PRIVATE_primitiveComparator), \n        /** Maps a target to its targetID. */\n        // TODO(wuandy): Evaluate if TargetId can be part of Target.\n        this.Yi = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), \n        /**\n         * A per collection group index of the last read time processed by\n         * `getNewDocumentChanges()`.\n         *\n         * PORTING NOTE: This is only used for multi-tab synchronization.\n         */\n        this.Zi = new Map, this.Xi = e.getRemoteDocumentCache(), this.kr = e.getTargetCache(), \n        this.Qr = e.getBundleCache(), this.es(n);\n    }\n    es(e) {\n        // TODO(indexing): Add spec tests that test these components change after a\n        // user change\n        this.documentOverlayCache = this.persistence.getDocumentOverlayCache(e), this.indexManager = this.persistence.getIndexManager(e), \n        this.mutationQueue = this.persistence.getMutationQueue(e, this.indexManager), this.localDocuments = new LocalDocumentsView(this.Xi, this.mutationQueue, this.documentOverlayCache, this.indexManager), \n        this.Xi.setIndexManager(this.indexManager), this.Hi.initialize(this.localDocuments, this.indexManager);\n    }\n    collectGarbage(e) {\n        return this.persistence.runTransaction(\"Collect garbage\", \"readwrite-primary\", (t => e.collect(t, this.Ji)));\n    }\n}\n\nfunction __PRIVATE_newLocalStore(\n/** Manages our in-memory or durable persistence. */\ne, t, n, r) {\n    return new __PRIVATE_LocalStoreImpl(e, t, n, r);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nasync function __PRIVATE_localStoreHandleUserChange(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    return await n.persistence.runTransaction(\"Handle user change\", \"readonly\", (e => {\n        // Swap out the mutation queue, grabbing the pending mutation batches\n        // before and after.\n        let r;\n        return n.mutationQueue.getAllMutationBatches(e).next((i => (r = i, n.es(t), n.mutationQueue.getAllMutationBatches(e)))).next((t => {\n            const i = [], s = [];\n            // Union the old/new changed keys.\n            let o = __PRIVATE_documentKeySet();\n            for (const e of r) {\n                i.push(e.batchId);\n                for (const t of e.mutations) o = o.add(t.key);\n            }\n            for (const e of t) {\n                s.push(e.batchId);\n                for (const t of e.mutations) o = o.add(t.key);\n            }\n            // Return the set of all (potentially) changed documents and the list\n            // of mutation batch IDs that were affected by change.\n                        return n.localDocuments.getDocuments(e, o).next((e => ({\n                ts: e,\n                removedBatchIds: i,\n                addedBatchIds: s\n            })));\n        }));\n    }));\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n *  + remove the batch from the mutation queue;\n *  + apply the changes to the remote document cache;\n *  + recalculate the latency compensated view implied by those changes (there\n *    may be mutations in the queue that affect the documents but haven't been\n *    acknowledged yet); and\n *  + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nfunction __PRIVATE_localStoreAcknowledgeBatch(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    return n.persistence.runTransaction(\"Acknowledge batch\", \"readwrite-primary\", (e => {\n        const r = t.batch.keys(), i = n.Xi.newChangeBuffer({\n            trackRemovals: !0\n        });\n        return function __PRIVATE_applyWriteToRemoteDocuments(e, t, n, r) {\n            const i = n.batch, s = i.keys();\n            let o = PersistencePromise.resolve();\n            return s.forEach((e => {\n                o = o.next((() => r.getEntry(t, e))).next((t => {\n                    const s = n.docVersions.get(e);\n                    __PRIVATE_hardAssert(null !== s), t.version.compareTo(s) < 0 && (i.applyToRemoteDocument(t, n), \n                    t.isValidDocument() && (\n                    // We use the commitVersion as the readTime rather than the\n                    // document's updateTime since the updateTime is not advanced\n                    // for updates that do not modify the underlying document.\n                    t.setReadTime(n.commitVersion), r.addEntry(t)));\n                }));\n            })), o.next((() => e.mutationQueue.removeMutationBatch(t, i)));\n        }\n        /** Returns the local view of the documents affected by a mutation batch. */\n        // PORTING NOTE: Multi-Tab only.\n        (n, e, t, i).next((() => i.apply(e))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, function __PRIVATE_getKeysWithTransformResults(e) {\n            let t = __PRIVATE_documentKeySet();\n            for (let n = 0; n < e.mutationResults.length; ++n) {\n                e.mutationResults[n].transformResults.length > 0 && (t = t.add(e.batch.mutations[n].key));\n            }\n            return t;\n        }\n        /**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */ (t)))).next((() => n.localDocuments.getDocuments(e, r)));\n    }));\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nfunction __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e) {\n    const t = __PRIVATE_debugCast(e);\n    return t.persistence.runTransaction(\"Get last remote snapshot version\", \"readonly\", (e => t.kr.getLastRemoteSnapshotVersion(e)));\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */ function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e, t) {\n    const n = __PRIVATE_debugCast(e), r = t.snapshotVersion;\n    let i = n.Ji;\n    return n.persistence.runTransaction(\"Apply remote event\", \"readwrite-primary\", (e => {\n        const s = n.Xi.newChangeBuffer({\n            trackRemovals: !0\n        });\n        // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n                i = n.Ji;\n        const o = [];\n        t.targetChanges.forEach(((s, _) => {\n            const a = i.get(_);\n            if (!a) return;\n            // Only update the remote keys if the target is still active. This\n            // ensures that we can persist the updated target data along with\n            // the updated assignment.\n                        o.push(n.kr.removeMatchingKeys(e, s.removedDocuments, _).next((() => n.kr.addMatchingKeys(e, s.addedDocuments, _))));\n            let u = a.withSequenceNumber(e.currentSequenceNumber);\n            null !== t.targetMismatches.get(_) ? u = u.withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()) : s.resumeToken.approximateByteSize() > 0 && (u = u.withResumeToken(s.resumeToken, r)), \n            i = i.insert(_, u), \n            // Update the target data if there are target changes (or if\n            // sufficient time has passed since the last update).\n            /**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\n            function __PRIVATE_shouldPersistTargetData(e, t, n) {\n                // Always persist target data if we don't already have a resume token.\n                if (0 === e.resumeToken.approximateByteSize()) return !0;\n                // Don't allow resume token changes to be buffered indefinitely. This\n                // allows us to be reasonably up-to-date after a crash and avoids needing\n                // to loop over all active queries on shutdown. Especially in the browser\n                // we may not get time to do anything interesting while the current tab is\n                // closing.\n                                if (t.snapshotVersion.toMicroseconds() - e.snapshotVersion.toMicroseconds() >= 3e8) return !0;\n                // Otherwise if the only thing that has changed about a target is its resume\n                // token it's not worth persisting. Note that the RemoteStore keeps an\n                // in-memory view of the currently active targets which includes the current\n                // resume token, so stream failure or user changes will still use an\n                // up-to-date resume token regardless of what we do here.\n                                return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;\n            }\n            /**\n * Notifies local store of the changed views to locally pin documents.\n */ (a, u, s) && o.push(n.kr.updateTargetData(e, u));\n        }));\n        let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();\n        // HACK: The only reason we allow a null snapshot version is so that we\n        // can synthesize remote events when we get permission denied errors while\n        // trying to resolve the state of a locally cached document that is in\n        // limbo.\n        if (t.documentUpdates.forEach((r => {\n            t.resolvedLimboDocuments.has(r) && o.push(n.persistence.referenceDelegate.updateLimboDocument(e, r));\n        })), \n        // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n        // the remote documents in advance in a single call.\n        o.push(__PRIVATE_populateDocumentChangeBuffer(e, s, t.documentUpdates).next((e => {\n            _ = e.ns, a = e.rs;\n        }))), !r.isEqual(SnapshotVersion.min())) {\n            const t = n.kr.getLastRemoteSnapshotVersion(e).next((t => n.kr.setTargetsMetadata(e, e.currentSequenceNumber, r)));\n            o.push(t);\n        }\n        return PersistencePromise.waitFor(o).next((() => s.apply(e))).next((() => n.localDocuments.getLocalViewOfDocuments(e, _, a))).next((() => _));\n    })).then((e => (n.Ji = i, e)));\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n *        applied to storage.\n * @param documents - Documents to be applied.\n */ function __PRIVATE_populateDocumentChangeBuffer(e, t, n) {\n    let r = __PRIVATE_documentKeySet(), i = __PRIVATE_documentKeySet();\n    return n.forEach((e => r = r.add(e))), t.getEntries(e, r).next((e => {\n        let r = __PRIVATE_mutableDocumentMap();\n        return n.forEach(((n, s) => {\n            const o = e.get(n);\n            // Check if see if there is a existence state change for this document.\n                        s.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)), \n            // Note: The order of the steps below is important, since we want\n            // to ensure that rejected limbo resolutions (which fabricate\n            // NoDocuments with SnapshotVersion.min()) never add documents to\n            // cache.\n            s.isNoDocument() && s.version.isEqual(SnapshotVersion.min()) ? (\n            // NoDocuments with SnapshotVersion.min() are used in manufactured\n            // events. We remove these documents from cache since we lost\n            // access.\n            t.removeEntry(n, s.readTime), r = r.insert(n, s)) : !o.isValidDocument() || s.version.compareTo(o.version) > 0 || 0 === s.version.compareTo(o.version) && o.hasPendingWrites ? (t.addEntry(s), \n            r = r.insert(n, s)) : __PRIVATE_logDebug(\"LocalStore\", \"Ignoring outdated watch update for \", n, \". Current version:\", o.version, \" Watch version:\", s.version);\n        })), {\n            ns: r,\n            rs: i\n        };\n    }));\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nfunction __PRIVATE_localStoreGetNextMutationBatch(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    return n.persistence.runTransaction(\"Get next mutation batch\", \"readonly\", (e => (void 0 === t && (t = -1), \n    n.mutationQueue.getNextMutationBatchAfterBatchId(e, t))));\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nfunction __PRIVATE_localStoreAllocateTarget(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    return n.persistence.runTransaction(\"Allocate target\", \"readwrite\", (e => {\n        let r;\n        return n.kr.getTargetData(e, t).next((i => i ? (\n        // This target has been listened to previously, so reuse the\n        // previous targetID.\n        // TODO(mcg): freshen last accessed date?\n        r = i, PersistencePromise.resolve(r)) : n.kr.allocateTargetId(e).next((i => (r = new TargetData(t, i, \"TargetPurposeListen\" /* TargetPurpose.Listen */ , e.currentSequenceNumber), \n        n.kr.addTargetData(e, r).next((() => r)))))));\n    })).then((e => {\n        // If Multi-Tab is enabled, the existing target data may be newer than\n        // the in-memory data\n        const r = n.Ji.get(e.targetId);\n        return (null === r || e.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.Ji = n.Ji.insert(e.targetId, e), \n        n.Yi.set(t, e.targetId)), e;\n    }));\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nasync function __PRIVATE_localStoreReleaseTarget(e, t, n) {\n    const r = __PRIVATE_debugCast(e), i = r.Ji.get(t), s = n ? \"readwrite\" : \"readwrite-primary\";\n    try {\n        n || await r.persistence.runTransaction(\"Release target\", s, (e => r.persistence.referenceDelegate.removeTarget(e, i)));\n    } catch (e) {\n        if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;\n        // All `releaseTarget` does is record the final metadata state for the\n        // target, but we've been recording this periodically during target\n        // activity. If we lose this write this could cause a very slight\n        // difference in the order of target deletion during GC, but we\n        // don't define exact LRU semantics so this is acceptable.\n        __PRIVATE_logDebug(\"LocalStore\", `Failed to update sequence numbers for target ${t}: ${e}`);\n    }\n    r.Ji = r.Ji.remove(t), r.Yi.delete(i.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */ function __PRIVATE_localStoreExecuteQuery(e, t, n) {\n    const r = __PRIVATE_debugCast(e);\n    let i = SnapshotVersion.min(), s = __PRIVATE_documentKeySet();\n    return r.persistence.runTransaction(\"Execute query\", \"readonly\", (e => function __PRIVATE_localStoreGetTargetData(e, t, n) {\n        const r = __PRIVATE_debugCast(e), i = r.Yi.get(n);\n        return void 0 !== i ? PersistencePromise.resolve(r.Ji.get(i)) : r.kr.getTargetData(t, n);\n    }(r, e, __PRIVATE_queryToTarget(t)).next((t => {\n        if (t) return i = t.lastLimboFreeSnapshotVersion, r.kr.getMatchingKeysForTargetId(e, t.targetId).next((e => {\n            s = e;\n        }));\n    })).next((() => r.Hi.getDocumentsMatchingQuery(e, t, n ? i : SnapshotVersion.min(), n ? s : __PRIVATE_documentKeySet()))).next((e => (__PRIVATE_setMaxReadTime(r, __PRIVATE_queryCollectionGroup(t), e), \n    {\n        documents: e,\n        ss: s\n    })))));\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_localStoreGetCachedTarget(e, t) {\n    const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.kr), i = n.Ji.get(t);\n    return i ? Promise.resolve(i.target) : n.persistence.runTransaction(\"Get target data\", \"readonly\", (e => r.ut(e, t).next((e => e ? e.target : null))));\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_localStoreGetNewDocumentChanges(e, t) {\n    const n = __PRIVATE_debugCast(e), r = n.Zi.get(t) || SnapshotVersion.min();\n    // Get the current maximum read time for the collection. This should always\n    // exist, but to reduce the chance for regressions we default to\n    // SnapshotVersion.Min()\n    // TODO(indexing): Consider removing the default value.\n        return n.persistence.runTransaction(\"Get new document changes\", \"readonly\", (e => n.Xi.getAllFromCollectionGroup(e, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, -1), \n    /* limit= */ Number.MAX_SAFE_INTEGER))).then((e => (__PRIVATE_setMaxReadTime(n, t, e), \n    e)));\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_setMaxReadTime(e, t, n) {\n    let r = e.Zi.get(t) || SnapshotVersion.min();\n    n.forEach(((e, t) => {\n        t.readTime.compareTo(r) > 0 && (r = t.readTime);\n    })), e.Zi.set(t, r);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nasync function __PRIVATE_localStoreApplyBundledDocuments(e, t, n, r) {\n    const i = __PRIVATE_debugCast(e);\n    let s = __PRIVATE_documentKeySet(), o = __PRIVATE_mutableDocumentMap();\n    for (const e of n) {\n        const n = t.os(e.metadata.name);\n        e.document && (s = s.add(n));\n        const r = t._s(e);\n        r.setReadTime(t.us(e.metadata.readTime)), o = o.insert(n, r);\n    }\n    const _ = i.Xi.newChangeBuffer({\n        trackRemovals: !0\n    }), a = await __PRIVATE_localStoreAllocateTarget(i, function __PRIVATE_umbrellaTarget(e) {\n        // It is OK that the path used for the query is not valid, because this will\n        // not be read and queried.\n        return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e}`)));\n    }(r));\n    // Allocates a target to hold all document keys from the bundle, such that\n    // they will not get garbage collected right away.\n        return i.persistence.runTransaction(\"Apply bundle documents\", \"readwrite\", (e => __PRIVATE_populateDocumentChangeBuffer(e, _, o).next((t => (_.apply(e), \n    t))).next((t => i.kr.removeMatchingKeysForTargetId(e, a.targetId).next((() => i.kr.addMatchingKeys(e, s, a.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(e, t.ns, t.rs))).next((() => t.ns))))));\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nasync function __PRIVATE_localStoreSaveNamedQuery(e, t, n = __PRIVATE_documentKeySet()) {\n    // Allocate a target for the named query such that it can be resumed\n    // from associated read time if users use it to listen.\n    // NOTE: this also means if no corresponding target exists, the new target\n    // will remain active and will not get collected, unless users happen to\n    // unlisten the query somehow.\n    const r = await __PRIVATE_localStoreAllocateTarget(e, __PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(t.bundledQuery))), i = __PRIVATE_debugCast(e);\n    return i.persistence.runTransaction(\"Save named query\", \"readwrite\", (e => {\n        const s = __PRIVATE_fromVersion(t.readTime);\n        // Simply save the query itself if it is older than what the SDK already\n        // has.\n                if (r.snapshotVersion.compareTo(s) >= 0) return i.Qr.saveNamedQuery(e, t);\n        // Update existing target data because the query from the bundle is newer.\n                const o = r.withResumeToken(ByteString.EMPTY_BYTE_STRING, s);\n        return i.Ji = i.Ji.insert(o.targetId, o), i.kr.updateTargetData(e, o).next((() => i.kr.removeMatchingKeysForTargetId(e, r.targetId))).next((() => i.kr.addMatchingKeys(e, n, r.targetId))).next((() => i.Qr.saveNamedQuery(e, t)));\n    }));\n}\n\n/** Assembles the key for a client state in WebStorage */\nfunction createWebStorageClientStateKey(e, t) {\n    return `firestore_clients_${e}_${t}`;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n//     firestore_mutations_<persistence_prefix>_<batch_id>\n//     (for unauthenticated users)\n// or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>\n\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\n/** Assembles the key for a mutation batch in WebStorage */\nfunction createWebStorageMutationBatchKey(e, t, n) {\n    let r = `firestore_mutations_${e}_${n}`;\n    return t.isAuthenticated() && (r += `_${t.uid}`), r;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n//     firestore_targets_<persistence_prefix>_<target_id>\n/** Assembles the key for a query state in WebStorage */\nfunction createWebStorageQueryTargetMetadataKey(e, t) {\n    return `firestore_targets_${e}_${t}`;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n//     firestore_online_state_<persistence_prefix>\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nclass __PRIVATE_MutationMetadata {\n    constructor(e, t, n, r) {\n        this.user = e, this.batchId = t, this.state = n, this.error = r;\n    }\n    /**\n     * Parses a MutationMetadata from its JSON representation in WebStorage.\n     * Logs a warning and returns null if the format of the data is not valid.\n     */    static cs(e, t, n) {\n        const r = JSON.parse(n);\n        let i, s = \"object\" == typeof r && -1 !== [ \"pending\", \"acknowledged\", \"rejected\" ].indexOf(r.state) && (void 0 === r.error || \"object\" == typeof r.error);\n        return s && r.error && (s = \"string\" == typeof r.error.message && \"string\" == typeof r.error.code, \n        s && (i = new FirestoreError(r.error.code, r.error.message))), s ? new __PRIVATE_MutationMetadata(e, t, r.state, i) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse mutation state for ID '${t}': ${n}`), \n        null);\n    }\n    ls() {\n        const e = {\n            state: this.state,\n            updateTimeMs: Date.now()\n        };\n        return this.error && (e.error = {\n            code: this.error.code,\n            message: this.error.message\n        }), JSON.stringify(e);\n    }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nclass __PRIVATE_QueryTargetMetadata {\n    constructor(e, t, n) {\n        this.targetId = e, this.state = t, this.error = n;\n    }\n    /**\n     * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n     * Logs a warning and returns null if the format of the data is not valid.\n     */    static cs(e, t) {\n        const n = JSON.parse(t);\n        let r, i = \"object\" == typeof n && -1 !== [ \"not-current\", \"current\", \"rejected\" ].indexOf(n.state) && (void 0 === n.error || \"object\" == typeof n.error);\n        return i && n.error && (i = \"string\" == typeof n.error.message && \"string\" == typeof n.error.code, \n        i && (r = new FirestoreError(n.error.code, n.error.message))), i ? new __PRIVATE_QueryTargetMetadata(e, n.state, r) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse target state for ID '${e}': ${t}`), \n        null);\n    }\n    ls() {\n        const e = {\n            state: this.state,\n            updateTimeMs: Date.now()\n        };\n        return this.error && (e.error = {\n            code: this.error.code,\n            message: this.error.message\n        }), JSON.stringify(e);\n    }\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */ class __PRIVATE_RemoteClientState {\n    constructor(e, t) {\n        this.clientId = e, this.activeTargetIds = t;\n    }\n    /**\n     * Parses a RemoteClientState from the JSON representation in WebStorage.\n     * Logs a warning and returns null if the format of the data is not valid.\n     */    static cs(e, t) {\n        const n = JSON.parse(t);\n        let r = \"object\" == typeof n && n.activeTargetIds instanceof Array, i = __PRIVATE_targetIdSet();\n        for (let e = 0; r && e < n.activeTargetIds.length; ++e) r = isSafeInteger(n.activeTargetIds[e]), \n        i = i.add(n.activeTargetIds[e]);\n        return r ? new __PRIVATE_RemoteClientState(e, i) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse client data for instance '${e}': ${t}`), \n        null);\n    }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */ class __PRIVATE_SharedOnlineState {\n    constructor(e, t) {\n        this.clientId = e, this.onlineState = t;\n    }\n    /**\n     * Parses a SharedOnlineState from its JSON representation in WebStorage.\n     * Logs a warning and returns null if the format of the data is not valid.\n     */    static cs(e) {\n        const t = JSON.parse(e);\n        return \"object\" == typeof t && -1 !== [ \"Unknown\", \"Online\", \"Offline\" ].indexOf(t.onlineState) && \"string\" == typeof t.clientId ? new __PRIVATE_SharedOnlineState(t.clientId, t.onlineState) : (__PRIVATE_logError(\"SharedClientState\", `Failed to parse online state: ${e}`), \n        null);\n    }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nclass __PRIVATE_LocalClientState {\n    constructor() {\n        this.activeTargetIds = __PRIVATE_targetIdSet();\n    }\n    hs(e) {\n        this.activeTargetIds = this.activeTargetIds.add(e);\n    }\n    Ps(e) {\n        this.activeTargetIds = this.activeTargetIds.delete(e);\n    }\n    /**\n     * Converts this entry into a JSON-encoded format we can use for WebStorage.\n     * Does not encode `clientId` as it is part of the key in WebStorage.\n     */    ls() {\n        const e = {\n            activeTargetIds: this.activeTargetIds.toArray(),\n            updateTimeMs: Date.now()\n        };\n        return JSON.stringify(e);\n    }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */ class __PRIVATE_WebStorageSharedClientState {\n    constructor(e, t, n, r, i) {\n        this.window = e, this.ii = t, this.persistenceKey = n, this.Is = r, this.syncEngine = null, \n        this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.Ts = this.Es.bind(this), \n        this.ds = new SortedMap(__PRIVATE_primitiveComparator), this.started = !1, \n        /**\n         * Captures WebStorage events that occur before `start()` is called. These\n         * events are replayed once `WebStorageSharedClientState` is started.\n         */\n        this.As = [];\n        // Escape the special characters mentioned here:\n        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n        const s = n.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n        this.storage = this.window.localStorage, this.currentUser = i, this.Rs = createWebStorageClientStateKey(this.persistenceKey, this.Is), \n        this.Vs = \n        /** Assembles the key for the current sequence number. */\n        function createWebStorageSequenceNumberKey(e) {\n            return `firestore_sequence_number_${e}`;\n        }\n        /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (this.persistenceKey), this.ds = this.ds.insert(this.Is, new __PRIVATE_LocalClientState), \n        this.fs = new RegExp(`^firestore_clients_${s}_([^_]*)$`), this.gs = new RegExp(`^firestore_mutations_${s}_(\\\\d+)(?:_(.*))?$`), \n        this.ps = new RegExp(`^firestore_targets_${s}_(\\\\d+)$`), this.ys = \n        /** Assembles the key for the online state of the primary tab. */\n        function createWebStorageOnlineStateKey(e) {\n            return `firestore_online_state_${e}`;\n        }\n        // The WebStorage prefix that plays as a event to indicate the remote documents\n        // might have changed due to some secondary tabs loading a bundle.\n        // format of the key is:\n        //     firestore_bundle_loaded_v2_<persistenceKey>\n        // The version ending with \"v2\" stores the list of modified collection groups.\n        (this.persistenceKey), this.ws = function createBundleLoadedKey(e) {\n            return `firestore_bundle_loaded_v2_${e}`;\n        }\n        // The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n        // looks like 'firestore_sequence_number_<persistence_prefix>'.\n        (this.persistenceKey), \n        // Rather than adding the storage observer during start(), we add the\n        // storage observer during initialization. This ensures that we collect\n        // events before other components populate their initial state (during their\n        // respective start() calls). Otherwise, we might for example miss a\n        // mutation that is added after LocalStore's start() processed the existing\n        // mutations but before we observe WebStorage events.\n        this.window.addEventListener(\"storage\", this.Ts);\n    }\n    /** Returns 'true' if WebStorage is available in the current environment. */    static v(e) {\n        return !(!e || !e.localStorage);\n    }\n    async start() {\n        // Retrieve the list of existing clients to backfill the data in\n        // SharedClientState.\n        const e = await this.syncEngine.Ni();\n        for (const t of e) {\n            if (t === this.Is) continue;\n            const e = this.getItem(createWebStorageClientStateKey(this.persistenceKey, t));\n            if (e) {\n                const n = __PRIVATE_RemoteClientState.cs(t, e);\n                n && (this.ds = this.ds.insert(n.clientId, n));\n            }\n        }\n        this.Ss();\n        // Check if there is an existing online state and call the callback handler\n        // if applicable.\n        const t = this.storage.getItem(this.ys);\n        if (t) {\n            const e = this.bs(t);\n            e && this.Ds(e);\n        }\n        for (const e of this.As) this.Es(e);\n        this.As = [], \n        // Register a window unload hook to remove the client metadata entry from\n        // WebStorage even if `shutdown()` was not called.\n        this.window.addEventListener(\"pagehide\", (() => this.shutdown())), this.started = !0;\n    }\n    writeSequenceNumber(e) {\n        this.setItem(this.Vs, JSON.stringify(e));\n    }\n    getAllActiveQueryTargets() {\n        return this.vs(this.ds);\n    }\n    isActiveQueryTarget(e) {\n        let t = !1;\n        return this.ds.forEach(((n, r) => {\n            r.activeTargetIds.has(e) && (t = !0);\n        })), t;\n    }\n    addPendingMutation(e) {\n        this.Cs(e, \"pending\");\n    }\n    updateMutationState(e, t, n) {\n        this.Cs(e, t, n), \n        // Once a final mutation result is observed by other clients, they no longer\n        // access the mutation's metadata entry. Since WebStorage replays events\n        // in order, it is safe to delete the entry right after updating it.\n        this.Fs(e);\n    }\n    addLocalQueryTarget(e) {\n        let t = \"not-current\";\n        // Lookup an existing query state if the target ID was already registered\n        // by another tab\n                if (this.isActiveQueryTarget(e)) {\n            const n = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));\n            if (n) {\n                const r = __PRIVATE_QueryTargetMetadata.cs(e, n);\n                r && (t = r.state);\n            }\n        }\n        return this.Ms.hs(e), this.Ss(), t;\n    }\n    removeLocalQueryTarget(e) {\n        this.Ms.Ps(e), this.Ss();\n    }\n    isLocalQueryTarget(e) {\n        return this.Ms.activeTargetIds.has(e);\n    }\n    clearQueryState(e) {\n        this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));\n    }\n    updateQueryState(e, t, n) {\n        this.xs(e, t, n);\n    }\n    handleUserChange(e, t, n) {\n        t.forEach((e => {\n            this.Fs(e);\n        })), this.currentUser = e, n.forEach((e => {\n            this.addPendingMutation(e);\n        }));\n    }\n    setOnlineState(e) {\n        this.Os(e);\n    }\n    notifyBundleLoaded(e) {\n        this.Ns(e);\n    }\n    shutdown() {\n        this.started && (this.window.removeEventListener(\"storage\", this.Ts), this.removeItem(this.Rs), \n        this.started = !1);\n    }\n    getItem(e) {\n        const t = this.storage.getItem(e);\n        return __PRIVATE_logDebug(\"SharedClientState\", \"READ\", e, t), t;\n    }\n    setItem(e, t) {\n        __PRIVATE_logDebug(\"SharedClientState\", \"SET\", e, t), this.storage.setItem(e, t);\n    }\n    removeItem(e) {\n        __PRIVATE_logDebug(\"SharedClientState\", \"REMOVE\", e), this.storage.removeItem(e);\n    }\n    Es(e) {\n        // Note: The function is typed to take Event to be interface-compatible with\n        // `Window.addEventListener`.\n        const t = e;\n        if (t.storageArea === this.storage) {\n            if (__PRIVATE_logDebug(\"SharedClientState\", \"EVENT\", t.key, t.newValue), t.key === this.Rs) return void __PRIVATE_logError(\"Received WebStorage notification for local change. Another client might have garbage-collected our state\");\n            this.ii.enqueueRetryable((async () => {\n                if (this.started) {\n                    if (null !== t.key) if (this.fs.test(t.key)) {\n                        if (null == t.newValue) {\n                            const e = this.Bs(t.key);\n                            return this.Ls(e, null);\n                        }\n                        {\n                            const e = this.ks(t.key, t.newValue);\n                            if (e) return this.Ls(e.clientId, e);\n                        }\n                    } else if (this.gs.test(t.key)) {\n                        if (null !== t.newValue) {\n                            const e = this.qs(t.key, t.newValue);\n                            if (e) return this.Qs(e);\n                        }\n                    } else if (this.ps.test(t.key)) {\n                        if (null !== t.newValue) {\n                            const e = this.Ks(t.key, t.newValue);\n                            if (e) return this.$s(e);\n                        }\n                    } else if (t.key === this.ys) {\n                        if (null !== t.newValue) {\n                            const e = this.bs(t.newValue);\n                            if (e) return this.Ds(e);\n                        }\n                    } else if (t.key === this.Vs) {\n                        const e = function __PRIVATE_fromWebStorageSequenceNumber(e) {\n                            let t = __PRIVATE_ListenSequence.ae;\n                            if (null != e) try {\n                                const n = JSON.parse(e);\n                                __PRIVATE_hardAssert(\"number\" == typeof n), t = n;\n                            } catch (e) {\n                                __PRIVATE_logError(\"SharedClientState\", \"Failed to read sequence number from WebStorage\", e);\n                            }\n                            return t;\n                        }\n                        /**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */ (t.newValue);\n                        e !== __PRIVATE_ListenSequence.ae && this.sequenceNumberHandler(e);\n                    } else if (t.key === this.ws) {\n                        const e = this.Us(t.newValue);\n                        await Promise.all(e.map((e => this.syncEngine.Ws(e))));\n                    }\n                } else this.As.push(t);\n            }));\n        }\n    }\n    get Ms() {\n        return this.ds.get(this.Is);\n    }\n    Ss() {\n        this.setItem(this.Rs, this.Ms.ls());\n    }\n    Cs(e, t, n) {\n        const r = new __PRIVATE_MutationMetadata(this.currentUser, e, t, n), i = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);\n        this.setItem(i, r.ls());\n    }\n    Fs(e) {\n        const t = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);\n        this.removeItem(t);\n    }\n    Os(e) {\n        const t = {\n            clientId: this.Is,\n            onlineState: e\n        };\n        this.storage.setItem(this.ys, JSON.stringify(t));\n    }\n    xs(e, t, n) {\n        const r = createWebStorageQueryTargetMetadataKey(this.persistenceKey, e), i = new __PRIVATE_QueryTargetMetadata(e, t, n);\n        this.setItem(r, i.ls());\n    }\n    Ns(e) {\n        const t = JSON.stringify(Array.from(e));\n        this.setItem(this.ws, t);\n    }\n    /**\n     * Parses a client state key in WebStorage. Returns null if the key does not\n     * match the expected key format.\n     */    Bs(e) {\n        const t = this.fs.exec(e);\n        return t ? t[1] : null;\n    }\n    /**\n     * Parses a client state in WebStorage. Returns 'null' if the value could not\n     * be parsed.\n     */    ks(e, t) {\n        const n = this.Bs(e);\n        return __PRIVATE_RemoteClientState.cs(n, t);\n    }\n    /**\n     * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n     * could not be parsed.\n     */    qs(e, t) {\n        const n = this.gs.exec(e), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;\n        return __PRIVATE_MutationMetadata.cs(new User(i), r, t);\n    }\n    /**\n     * Parses a query target state from WebStorage. Returns 'null' if the value\n     * could not be parsed.\n     */    Ks(e, t) {\n        const n = this.ps.exec(e), r = Number(n[1]);\n        return __PRIVATE_QueryTargetMetadata.cs(r, t);\n    }\n    /**\n     * Parses an online state from WebStorage. Returns 'null' if the value\n     * could not be parsed.\n     */    bs(e) {\n        return __PRIVATE_SharedOnlineState.cs(e);\n    }\n    Us(e) {\n        return JSON.parse(e);\n    }\n    async Qs(e) {\n        if (e.user.uid === this.currentUser.uid) return this.syncEngine.Gs(e.batchId, e.state, e.error);\n        __PRIVATE_logDebug(\"SharedClientState\", `Ignoring mutation for non-active user ${e.user.uid}`);\n    }\n    $s(e) {\n        return this.syncEngine.zs(e.targetId, e.state, e.error);\n    }\n    Ls(e, t) {\n        const n = t ? this.ds.insert(e, t) : this.ds.remove(e), r = this.vs(this.ds), i = this.vs(n), s = [], o = [];\n        return i.forEach((e => {\n            r.has(e) || s.push(e);\n        })), r.forEach((e => {\n            i.has(e) || o.push(e);\n        })), this.syncEngine.js(s, o).then((() => {\n            this.ds = n;\n        }));\n    }\n    Ds(e) {\n        // We check whether the client that wrote this online state is still active\n        // by comparing its client ID to the list of clients kept active in\n        // IndexedDb. If a client does not update their IndexedDb client state\n        // within 5 seconds, it is considered inactive and we don't emit an online\n        // state event.\n        this.ds.get(e.clientId) && this.onlineStateHandler(e.onlineState);\n    }\n    vs(e) {\n        let t = __PRIVATE_targetIdSet();\n        return e.forEach(((e, n) => {\n            t = t.unionWith(n.activeTargetIds);\n        })), t;\n    }\n}\n\nclass __PRIVATE_MemorySharedClientState {\n    constructor() {\n        this.Hs = new __PRIVATE_LocalClientState, this.Js = {}, this.onlineStateHandler = null, \n        this.sequenceNumberHandler = null;\n    }\n    addPendingMutation(e) {\n        // No op.\n    }\n    updateMutationState(e, t, n) {\n        // No op.\n    }\n    addLocalQueryTarget(e) {\n        return this.Hs.hs(e), this.Js[e] || \"not-current\";\n    }\n    updateQueryState(e, t, n) {\n        this.Js[e] = t;\n    }\n    removeLocalQueryTarget(e) {\n        this.Hs.Ps(e);\n    }\n    isLocalQueryTarget(e) {\n        return this.Hs.activeTargetIds.has(e);\n    }\n    clearQueryState(e) {\n        delete this.Js[e];\n    }\n    getAllActiveQueryTargets() {\n        return this.Hs.activeTargetIds;\n    }\n    isActiveQueryTarget(e) {\n        return this.Hs.activeTargetIds.has(e);\n    }\n    start() {\n        return this.Hs = new __PRIVATE_LocalClientState, Promise.resolve();\n    }\n    handleUserChange(e, t, n) {\n        // No op.\n    }\n    setOnlineState(e) {\n        // No op.\n    }\n    shutdown() {}\n    writeSequenceNumber(e) {}\n    notifyBundleLoaded(e) {\n        // No op.\n    }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_NoopConnectivityMonitor {\n    Ys(e) {\n        // No-op.\n    }\n    shutdown() {\n        // No-op.\n    }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nclass __PRIVATE_BrowserConnectivityMonitor {\n    constructor() {\n        this.Zs = () => this.Xs(), this.eo = () => this.no(), this.ro = [], this.io();\n    }\n    Ys(e) {\n        this.ro.push(e);\n    }\n    shutdown() {\n        window.removeEventListener(\"online\", this.Zs), window.removeEventListener(\"offline\", this.eo);\n    }\n    io() {\n        window.addEventListener(\"online\", this.Zs), window.addEventListener(\"offline\", this.eo);\n    }\n    Xs() {\n        __PRIVATE_logDebug(\"ConnectivityMonitor\", \"Network connectivity changed: AVAILABLE\");\n        for (const e of this.ro) e(0 /* NetworkStatus.AVAILABLE */);\n    }\n    no() {\n        __PRIVATE_logDebug(\"ConnectivityMonitor\", \"Network connectivity changed: UNAVAILABLE\");\n        for (const e of this.ro) e(1 /* NetworkStatus.UNAVAILABLE */);\n    }\n    // TODO(chenbrian): Consider passing in window either into this component or\n    // here for testing via FakeWindow.\n    /** Checks that all used attributes of window are available. */\n    static v() {\n        return \"undefined\" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;\n    }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */ let Re = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nfunction __PRIVATE_generateUniqueDebugId() {\n    return null === Re ? Re = function __PRIVATE_generateInitialUniqueDebugId() {\n        return 268435456 + Math.round(2147483648 * Math.random());\n    }() : Re++, \"0x\" + Re.toString(16);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ve = {\n    BatchGetDocuments: \"batchGet\",\n    Commit: \"commit\",\n    RunQuery: \"runQuery\",\n    RunAggregationQuery: \"runAggregationQuery\"\n};\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nclass __PRIVATE_StreamBridge {\n    constructor(e) {\n        this.so = e.so, this.oo = e.oo;\n    }\n    _o(e) {\n        this.ao = e;\n    }\n    uo(e) {\n        this.co = e;\n    }\n    onMessage(e) {\n        this.lo = e;\n    }\n    close() {\n        this.oo();\n    }\n    send(e) {\n        this.so(e);\n    }\n    ho() {\n        this.ao();\n    }\n    Po(e) {\n        this.co(e);\n    }\n    Io(e) {\n        this.lo(e);\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const me = \"WebChannelConnection\";\n\nclass __PRIVATE_WebChannelConnection extends \n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nclass __PRIVATE_RestConnection {\n    constructor(e) {\n        this.databaseInfo = e, this.databaseId = e.databaseId;\n        const t = e.ssl ? \"https\" : \"http\", n = encodeURIComponent(this.databaseId.projectId), r = encodeURIComponent(this.databaseId.database);\n        this.To = t + \"://\" + e.host, this.Eo = `projects/${n}/databases/${r}`, this.Ao = \"(default)\" === this.databaseId.database ? `project_id=${n}` : `project_id=${n}&database_id=${r}`;\n    }\n    get Ro() {\n        // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n        // where to run the query, and expect the `request` to NOT specify the \"path\".\n        return !1;\n    }\n    Vo(e, t, n, r, i) {\n        const s = __PRIVATE_generateUniqueDebugId(), o = this.mo(e, t);\n        __PRIVATE_logDebug(\"RestConnection\", `Sending RPC '${e}' ${s}:`, o, n);\n        const _ = {\n            \"google-cloud-resource-prefix\": this.Eo,\n            \"x-goog-request-params\": this.Ao\n        };\n        return this.fo(_, r, i), this.po(e, o, _, n).then((t => (__PRIVATE_logDebug(\"RestConnection\", `Received RPC '${e}' ${s}: `, t), \n        t)), (t => {\n            throw __PRIVATE_logWarn(\"RestConnection\", `RPC '${e}' ${s} failed with error: `, t, \"url: \", o, \"request:\", n), \n            t;\n        }));\n    }\n    yo(e, t, n, r, i, s) {\n        // The REST API automatically aggregates all of the streamed results, so we\n        // can just use the normal invoke() method.\n        return this.Vo(e, t, n, r, i);\n    }\n    /**\n     * Modifies the headers for a request, adding any authorization token if\n     * present and any additional headers for the request.\n     */    fo(e, t, n) {\n        e[\"X-Goog-Api-Client\"] = \n        // SDK_VERSION is updated to different value at runtime depending on the entry point,\n        // so we need to get its value when we need it in a function.\n        function __PRIVATE_getGoogApiClientValue() {\n            return \"gl-js/ fire/\" + b;\n        }(), \n        // Content-Type: text/plain will avoid preflight requests which might\n        // mess with CORS and redirects by proxies. If we add custom headers\n        // we will need to change this code to potentially use the $httpOverwrite\n        // parameter supported by ESF to avoid triggering preflight requests.\n        e[\"Content-Type\"] = \"text/plain\", this.databaseInfo.appId && (e[\"X-Firebase-GMPID\"] = this.databaseInfo.appId), \n        t && t.headers.forEach(((t, n) => e[n] = t)), n && n.headers.forEach(((t, n) => e[n] = t));\n    }\n    mo(e, t) {\n        const n = Ve[e];\n        return `${this.To}/v1/${t}:${n}`;\n    }\n} {\n    constructor(e) {\n        super(e), this.forceLongPolling = e.forceLongPolling, this.autoDetectLongPolling = e.autoDetectLongPolling, \n        this.useFetchStreams = e.useFetchStreams, this.longPollingOptions = e.longPollingOptions;\n    }\n    po(e, t, n, r) {\n        const i = __PRIVATE_generateUniqueDebugId();\n        return new Promise(((s, o) => {\n            const _ = new XhrIo;\n            _.setWithCredentials(!0), _.listenOnce(EventType.COMPLETE, (() => {\n                try {\n                    switch (_.getLastErrorCode()) {\n                      case ErrorCode.NO_ERROR:\n                        const t = _.getResponseJson();\n                        __PRIVATE_logDebug(me, `XHR for RPC '${e}' ${i} received:`, JSON.stringify(t)), \n                        s(t);\n                        break;\n\n                      case ErrorCode.TIMEOUT:\n                        __PRIVATE_logDebug(me, `RPC '${e}' ${i} timed out`), o(new FirestoreError(v.DEADLINE_EXCEEDED, \"Request time out\"));\n                        break;\n\n                      case ErrorCode.HTTP_ERROR:\n                        const n = _.getStatus();\n                        if (__PRIVATE_logDebug(me, `RPC '${e}' ${i} failed with status:`, n, \"response text:\", _.getResponseText()), \n                        n > 0) {\n                            let e = _.getResponseJson();\n                            Array.isArray(e) && (e = e[0]);\n                            const t = null == e ? void 0 : e.error;\n                            if (t && t.status && t.message) {\n                                const e = function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e) {\n                                    const t = e.toLowerCase().replace(/_/g, \"-\");\n                                    return Object.values(v).indexOf(t) >= 0 ? t : v.UNKNOWN;\n                                }(t.status);\n                                o(new FirestoreError(e, t.message));\n                            } else o(new FirestoreError(v.UNKNOWN, \"Server responded with status \" + _.getStatus()));\n                        } else \n                        // If we received an HTTP_ERROR but there's no status code,\n                        // it's most probably a connection issue\n                        o(new FirestoreError(v.UNAVAILABLE, \"Connection failed.\"));\n                        break;\n\n                      default:\n                        fail();\n                    }\n                } finally {\n                    __PRIVATE_logDebug(me, `RPC '${e}' ${i} completed.`);\n                }\n            }));\n            const a = JSON.stringify(r);\n            __PRIVATE_logDebug(me, `RPC '${e}' ${i} sending request:`, r), _.send(t, \"POST\", a, n, 15);\n        }));\n    }\n    wo(e, t, n) {\n        const r = __PRIVATE_generateUniqueDebugId(), i = [ this.To, \"/\", \"google.firestore.v1.Firestore\", \"/\", e, \"/channel\" ], s = createWebChannelTransport(), o = getStatEventTarget(), _ = {\n            // Required for backend stickiness, routing behavior is based on this\n            // parameter.\n            httpSessionIdParam: \"gsessionid\",\n            initMessageHeaders: {},\n            messageUrlParams: {\n                // This param is used to improve routing and project isolation by the\n                // backend and must be included in every request.\n                database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n            },\n            sendRawJson: !0,\n            supportsCrossDomainXhr: !0,\n            internalChannelParams: {\n                // Override the default timeout (randomized between 10-20 seconds) since\n                // a large write batch on a slow internet connection may take a long\n                // time to send to the backend. Rather than have WebChannel impose a\n                // tight timeout which could lead to infinite timeouts and retries, we\n                // set it very large (5-10 minutes) and rely on the browser's builtin\n                // timeouts to kick in if the request isn't working.\n                forwardChannelRequestTimeoutMs: 6e5\n            },\n            forceLongPolling: this.forceLongPolling,\n            detectBufferingProxy: this.autoDetectLongPolling\n        }, a = this.longPollingOptions.timeoutSeconds;\n        void 0 !== a && (_.longPollingTimeout = Math.round(1e3 * a)), this.useFetchStreams && (_.xmlHttpFactory = new FetchXmlHttpFactory({})), \n        this.fo(_.initMessageHeaders, t, n), \n        // Sending the custom headers we just added to request.initMessageHeaders\n        // (Authorization, etc.) will trigger the browser to make a CORS preflight\n        // request because the XHR will no longer meet the criteria for a \"simple\"\n        // CORS request:\n        // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n        // Therefore to avoid the CORS preflight request (an extra network\n        // roundtrip), we use the encodeInitMessageHeaders option to specify that\n        // the headers should instead be encoded in the request's POST payload,\n        // which is recognized by the webchannel backend.\n        _.encodeInitMessageHeaders = !0;\n        const u = i.join(\"\");\n        __PRIVATE_logDebug(me, `Creating RPC '${e}' stream ${r}: ${u}`, _);\n        const c = s.createWebChannel(u, _);\n        // WebChannel supports sending the first message with the handshake - saving\n        // a network round trip. However, it will have to call send in the same\n        // JS event loop as open. In order to enforce this, we delay actually\n        // opening the WebChannel until send is called. Whether we have called\n        // open is tracked with this variable.\n                let l = !1, h = !1;\n        // A flag to determine whether the stream was closed (by us or through an\n        // error/close event) to avoid delivering multiple close events or sending\n        // on a closed stream\n                const P = new __PRIVATE_StreamBridge({\n            so: t => {\n                h ? __PRIVATE_logDebug(me, `Not sending because RPC '${e}' stream ${r} is closed:`, t) : (l || (__PRIVATE_logDebug(me, `Opening RPC '${e}' stream ${r} transport.`), \n                c.open(), l = !0), __PRIVATE_logDebug(me, `RPC '${e}' stream ${r} sending:`, t), \n                c.send(t));\n            },\n            oo: () => c.close()\n        }), __PRIVATE_unguardedEventListen = (e, t, n) => {\n            // TODO(dimond): closure typing seems broken because WebChannel does\n            // not implement goog.events.Listenable\n            e.listen(t, (e => {\n                try {\n                    n(e);\n                } catch (e) {\n                    setTimeout((() => {\n                        throw e;\n                    }), 0);\n                }\n            }));\n        };\n        // Closure events are guarded and exceptions are swallowed, so catch any\n        // exception and rethrow using a setTimeout so they become visible again.\n        // Note that eventually this function could go away if we are confident\n        // enough the code is exception free.\n                return __PRIVATE_unguardedEventListen(c, WebChannel.EventType.OPEN, (() => {\n            h || __PRIVATE_logDebug(me, `RPC '${e}' stream ${r} transport opened.`);\n        })), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.CLOSE, (() => {\n            h || (h = !0, __PRIVATE_logDebug(me, `RPC '${e}' stream ${r} transport closed`), \n            P.Po());\n        })), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.ERROR, (t => {\n            h || (h = !0, __PRIVATE_logWarn(me, `RPC '${e}' stream ${r} transport errored:`, t), \n            P.Po(new FirestoreError(v.UNAVAILABLE, \"The operation could not be completed\")));\n        })), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.MESSAGE, (t => {\n            var n;\n            if (!h) {\n                const i = t.data[0];\n                __PRIVATE_hardAssert(!!i);\n                // TODO(b/35143891): There is a bug in One Platform that caused errors\n                // (and only errors) to be wrapped in an extra array. To be forward\n                // compatible with the bug we need to check either condition. The latter\n                // can be removed once the fix has been rolled out.\n                // Use any because msgData.error is not typed.\n                const s = i, o = s.error || (null === (n = s[0]) || void 0 === n ? void 0 : n.error);\n                if (o) {\n                    __PRIVATE_logDebug(me, `RPC '${e}' stream ${r} received error:`, o);\n                    // error.status will be a string like 'OK' or 'NOT_FOUND'.\n                    const t = o.status;\n                    let n = \n                    /**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n *     there is no match.\n */\n                    function __PRIVATE_mapCodeFromRpcStatus(e) {\n                        // lookup by string\n                        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                        const t = ue[e];\n                        if (void 0 !== t) return __PRIVATE_mapCodeFromRpcCode(t);\n                    }(t), i = o.message;\n                    void 0 === n && (n = v.INTERNAL, i = \"Unknown error status: \" + t + \" with message \" + o.message), \n                    // Mark closed so no further events are propagated\n                    h = !0, P.Po(new FirestoreError(n, i)), c.close();\n                } else __PRIVATE_logDebug(me, `RPC '${e}' stream ${r} received:`, i), P.Io(i);\n            }\n        })), __PRIVATE_unguardedEventListen(o, Event.STAT_EVENT, (t => {\n            t.stat === Stat.PROXY ? __PRIVATE_logDebug(me, `RPC '${e}' stream ${r} detected buffering proxy`) : t.stat === Stat.NOPROXY && __PRIVATE_logDebug(me, `RPC '${e}' stream ${r} detected no buffering proxy`);\n        })), setTimeout((() => {\n            // Technically we could/should wait for the WebChannel opened event,\n            // but because we want to send the first message with the WebChannel\n            // handshake we pretend the channel opened here (asynchronously), and\n            // then delay the actual open until the first message is sent.\n            P.ho();\n        }), 0), P;\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Initializes the WebChannelConnection for the browser. */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** The Platform's 'window' implementation or null if not available. */\nfunction __PRIVATE_getWindow() {\n    // `window` is not always available, e.g. in ReactNative and WebWorkers.\n    // eslint-disable-next-line no-restricted-globals\n    return \"undefined\" != typeof window ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */ function getDocument() {\n    // `document` is not always available, e.g. in ReactNative and WebWorkers.\n    // eslint-disable-next-line no-restricted-globals\n    return \"undefined\" != typeof document ? document : null;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function __PRIVATE_newSerializer(e) {\n    return new JsonProtoSerializer(e, /* useProto3Json= */ !0);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nclass __PRIVATE_ExponentialBackoff {\n    constructor(\n    /**\n     * The AsyncQueue to run backoff operations on.\n     */\n    e, \n    /**\n     * The ID to use when scheduling backoff operations on the AsyncQueue.\n     */\n    t, \n    /**\n     * The initial delay (used as the base delay on the first retry attempt).\n     * Note that jitter will still be applied, so the actual delay could be as\n     * little as 0.5*initialDelayMs.\n     */\n    n = 1e3\n    /**\n     * The multiplier to use to determine the extended base delay after each\n     * attempt.\n     */ , r = 1.5\n    /**\n     * The maximum base delay after which no further backoff is performed.\n     * Note that jitter will still be applied, so the actual delay could be as\n     * much as 1.5*maxDelayMs.\n     */ , i = 6e4) {\n        this.ii = e, this.timerId = t, this.So = n, this.bo = r, this.Do = i, this.vo = 0, \n        this.Co = null, \n        /** The last backoff attempt, as epoch milliseconds. */\n        this.Fo = Date.now(), this.reset();\n    }\n    /**\n     * Resets the backoff delay.\n     *\n     * The very next backoffAndWait() will have no delay. If it is called again\n     * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n     * subsequent ones will increase according to the backoffFactor.\n     */    reset() {\n        this.vo = 0;\n    }\n    /**\n     * Resets the backoff delay to the maximum delay (e.g. for use after a\n     * RESOURCE_EXHAUSTED error).\n     */    Mo() {\n        this.vo = this.Do;\n    }\n    /**\n     * Returns a promise that resolves after currentDelayMs, and increases the\n     * delay for any subsequent attempts. If there was a pending backoff operation\n     * already, it will be canceled.\n     */    xo(e) {\n        // Cancel any pending backoff operation.\n        this.cancel();\n        // First schedule using the current base (which may be 0 and should be\n        // honored as such).\n        const t = Math.floor(this.vo + this.Oo()), n = Math.max(0, Date.now() - this.Fo), r = Math.max(0, t - n);\n        // Guard against lastAttemptTime being in the future due to a clock change.\n                r > 0 && __PRIVATE_logDebug(\"ExponentialBackoff\", `Backing off for ${r} ms (base delay: ${this.vo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`), \n        this.Co = this.ii.enqueueAfterDelay(this.timerId, r, (() => (this.Fo = Date.now(), \n        e()))), \n        // Apply backoff factor to determine next delay and ensure it is within\n        // bounds.\n        this.vo *= this.bo, this.vo < this.So && (this.vo = this.So), this.vo > this.Do && (this.vo = this.Do);\n    }\n    No() {\n        null !== this.Co && (this.Co.skipDelay(), this.Co = null);\n    }\n    cancel() {\n        null !== this.Co && (this.Co.cancel(), this.Co = null);\n    }\n    /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */    Oo() {\n        return (Math.random() - .5) * this.vo;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n *   - Exponential backoff on failure\n *   - Authentication via CredentialsProvider\n *   - Dispatching all callbacks into the shared worker queue\n *   - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n *  SendType: The type of the outgoing message of the underlying\n *    connection stream\n *  ReceiveType: The type of the incoming message of the underlying\n *    connection stream\n *  ListenerType: The type of the listener that will be used for callbacks\n */\nclass __PRIVATE_PersistentStream {\n    constructor(e, t, n, r, i, s, o, _) {\n        this.ii = e, this.Bo = n, this.Lo = r, this.connection = i, this.authCredentialsProvider = s, \n        this.appCheckCredentialsProvider = o, this.listener = _, this.state = 0 /* PersistentStreamState.Initial */ , \n        /**\n         * A close count that's incremented every time the stream is closed; used by\n         * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n         * close.\n         */\n        this.ko = 0, this.qo = null, this.Qo = null, this.stream = null, this.Ko = new __PRIVATE_ExponentialBackoff(e, t);\n    }\n    /**\n     * Returns true if start() has been called and no error has occurred. True\n     * indicates the stream is open or in the process of opening (which\n     * encompasses respecting backoff, getting auth tokens, and starting the\n     * actual RPC). Use isOpen() to determine if the stream is open and ready for\n     * outbound requests.\n     */    $o() {\n        return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.Uo();\n    }\n    /**\n     * Returns true if the underlying RPC is open (the onOpen() listener has been\n     * called) and the stream is ready for outbound requests.\n     */    Uo() {\n        return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;\n    }\n    /**\n     * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n     * not immediately ready for use: onOpen() will be invoked when the RPC is\n     * ready for outbound requests, at which point isOpen() will return true.\n     *\n     * When start returns, isStarted() will return true.\n     */    start() {\n        4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Wo();\n    }\n    /**\n     * Stops the RPC. This call is idempotent and allowed regardless of the\n     * current isStarted() state.\n     *\n     * When stop returns, isStarted() and isOpen() will both return false.\n     */    async stop() {\n        this.$o() && await this.close(0 /* PersistentStreamState.Initial */);\n    }\n    /**\n     * After an error the stream will usually back off on the next attempt to\n     * start it. If the error warrants an immediate restart of the stream, the\n     * sender can use this to indicate that the receiver should not back off.\n     *\n     * Each error will call the onClose() listener. That function can decide to\n     * inhibit backoff if required.\n     */    Go() {\n        this.state = 0 /* PersistentStreamState.Initial */ , this.Ko.reset();\n    }\n    /**\n     * Marks this stream as idle. If no further actions are performed on the\n     * stream for one minute, the stream will automatically close itself and\n     * notify the stream's onClose() handler with Status.OK. The stream will then\n     * be in a !isStarted() state, requiring the caller to start the stream again\n     * before further use.\n     *\n     * Only streams that are in state 'Open' can be marked idle, as all other\n     * states imply pending network operations.\n     */    zo() {\n        // Starts the idle time if we are in state 'Open' and are not yet already\n        // running a timer (in which case the previous idle timeout still applies).\n        this.Uo() && null === this.qo && (this.qo = this.ii.enqueueAfterDelay(this.Bo, 6e4, (() => this.jo())));\n    }\n    /** Sends a message to the underlying stream. */    Ho(e) {\n        this.Jo(), this.stream.send(e);\n    }\n    /** Called by the idle timer when the stream should close due to inactivity. */    async jo() {\n        if (this.Uo()) \n        // When timing out an idle stream there's no reason to force the stream into backoff when\n        // it restarts so set the stream state to Initial instead of Error.\n        return this.close(0 /* PersistentStreamState.Initial */);\n    }\n    /** Marks the stream as active again. */    Jo() {\n        this.qo && (this.qo.cancel(), this.qo = null);\n    }\n    /** Cancels the health check delayed operation. */    Yo() {\n        this.Qo && (this.Qo.cancel(), this.Qo = null);\n    }\n    /**\n     * Closes the stream and cleans up as necessary:\n     *\n     * * closes the underlying GRPC stream;\n     * * calls the onClose handler with the given 'error';\n     * * sets internal stream state to 'finalState';\n     * * adjusts the backoff timer based on the error\n     *\n     * A new stream can be opened by calling start().\n     *\n     * @param finalState - the intended state of the stream after closing.\n     * @param error - the error the connection was closed with.\n     */    async close(e, t) {\n        // Cancel any outstanding timers (they're guaranteed not to execute).\n        this.Jo(), this.Yo(), this.Ko.cancel(), \n        // Invalidates any stream-related callbacks (e.g. from auth or the\n        // underlying stream), guaranteeing they won't execute.\n        this.ko++, 4 /* PersistentStreamState.Error */ !== e ? \n        // If this is an intentional close ensure we don't delay our next connection attempt.\n        this.Ko.reset() : t && t.code === v.RESOURCE_EXHAUSTED ? (\n        // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n        __PRIVATE_logError(t.toString()), __PRIVATE_logError(\"Using maximum backoff delay to prevent overloading the backend.\"), \n        this.Ko.Mo()) : t && t.code === v.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (\n        // \"unauthenticated\" error means the token was rejected. This should rarely\n        // happen since both Auth and AppCheck ensure a sufficient TTL when we\n        // request a token. If a user manually resets their system clock this can\n        // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n        // before we received the first message and we need to invalidate the token\n        // to ensure that we fetch a new token.\n        this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), \n        // Clean up the underlying stream because we are no longer interested in events.\n        null !== this.stream && (this.Zo(), this.stream.close(), this.stream = null), \n        // This state must be assigned before calling onClose() to allow the callback to\n        // inhibit backoff or otherwise manipulate the state in its non-started state.\n        this.state = e, \n        // Notify the listener that the stream closed.\n        await this.listener.uo(t);\n    }\n    /**\n     * Can be overridden to perform additional cleanup before the stream is closed.\n     * Calling super.tearDown() is not required.\n     */    Zo() {}\n    auth() {\n        this.state = 1 /* PersistentStreamState.Starting */;\n        const e = this.Xo(this.ko), t = this.ko;\n        // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n                Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([e, n]) => {\n            // Stream can be stopped while waiting for authentication.\n            // TODO(mikelehen): We really should just use dispatchIfNotClosed\n            // and let this dispatch onto the queue, but that opened a spec test can\n            // of worms that I don't want to deal with in this PR.\n            this.ko === t && \n            // Normally we'd have to schedule the callback on the AsyncQueue.\n            // However, the following calls are safe to be called outside the\n            // AsyncQueue since they don't chain asynchronous calls\n            this.e_(e, n);\n        }), (t => {\n            e((() => {\n                const e = new FirestoreError(v.UNKNOWN, \"Fetching auth token failed: \" + t.message);\n                return this.t_(e);\n            }));\n        }));\n    }\n    e_(e, t) {\n        const n = this.Xo(this.ko);\n        this.stream = this.n_(e, t), this.stream._o((() => {\n            n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Qo = this.ii.enqueueAfterDelay(this.Lo, 1e4, (() => (this.Uo() && (this.state = 3 /* PersistentStreamState.Healthy */), \n            Promise.resolve()))), this.listener._o())));\n        })), this.stream.uo((e => {\n            n((() => this.t_(e)));\n        })), this.stream.onMessage((e => {\n            n((() => this.onMessage(e)));\n        }));\n    }\n    Wo() {\n        this.state = 5 /* PersistentStreamState.Backoff */ , this.Ko.xo((async () => {\n            this.state = 0 /* PersistentStreamState.Initial */ , this.start();\n        }));\n    }\n    // Visible for tests\n    t_(e) {\n        // In theory the stream could close cleanly, however, in our current model\n        // we never expect this to happen because if we stop a stream ourselves,\n        // this callback will never be called. To prevent cases where we retry\n        // without a backoff accidentally, we set the stream to error in all cases.\n        return __PRIVATE_logDebug(\"PersistentStream\", `close with error: ${e}`), this.stream = null, \n        this.close(4 /* PersistentStreamState.Error */ , e);\n    }\n    /**\n     * Returns a \"dispatcher\" function that dispatches operations onto the\n     * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n     * us to turn auth / stream callbacks into no-ops if the stream is closed /\n     * re-opened, etc.\n     */    Xo(e) {\n        return t => {\n            this.ii.enqueueAndForget((() => this.ko === e ? t() : (__PRIVATE_logDebug(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), \n            Promise.resolve())));\n        };\n    }\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */ class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream {\n    constructor(e, t, n, r, i, s) {\n        super(e, \"listen_stream_connection_backoff\" /* TimerId.ListenStreamConnectionBackoff */ , \"listen_stream_idle\" /* TimerId.ListenStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , t, n, r, s), \n        this.serializer = i;\n    }\n    n_(e, t) {\n        return this.connection.wo(\"Listen\", e, t);\n    }\n    onMessage(e) {\n        // A successful response means the stream is healthy\n        this.Ko.reset();\n        const t = __PRIVATE_fromWatchChange(this.serializer, e), n = function __PRIVATE_versionFromListenResponse(e) {\n            // We have only reached a consistent snapshot for the entire stream if there\n            // is a read_time set and it applies to all targets (i.e. the list of\n            // targets is empty). The backend is guaranteed to send such responses.\n            if (!(\"targetChange\" in e)) return SnapshotVersion.min();\n            const t = e.targetChange;\n            return t.targetIds && t.targetIds.length ? SnapshotVersion.min() : t.readTime ? __PRIVATE_fromVersion(t.readTime) : SnapshotVersion.min();\n        }(e);\n        return this.listener.r_(t, n);\n    }\n    /**\n     * Registers interest in the results of the given target. If the target\n     * includes a resumeToken it will be included in the request. Results that\n     * affect the target will be streamed back as WatchChange messages that\n     * reference the targetId.\n     */    i_(e) {\n        const t = {};\n        t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.addTarget = function __PRIVATE_toTarget(e, t) {\n            let n;\n            const r = t.target;\n            if (n = __PRIVATE_targetIsDocumentTarget(r) ? {\n                documents: __PRIVATE_toDocumentsTarget(e, r)\n            } : {\n                query: __PRIVATE_toQueryTarget(e, r)\n            }, n.targetId = t.targetId, t.resumeToken.approximateByteSize() > 0) {\n                n.resumeToken = __PRIVATE_toBytes(e, t.resumeToken);\n                const r = __PRIVATE_toInt32Proto(e, t.expectedCount);\n                null !== r && (n.expectedCount = r);\n            } else if (t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n                // TODO(wuandy): Consider removing above check because it is most likely true.\n                // Right now, many tests depend on this behaviour though (leaving min() out\n                // of serialization).\n                n.readTime = toTimestamp(e, t.snapshotVersion.toTimestamp());\n                const r = __PRIVATE_toInt32Proto(e, t.expectedCount);\n                null !== r && (n.expectedCount = r);\n            }\n            return n;\n        }(this.serializer, e);\n        const n = __PRIVATE_toListenRequestLabels(this.serializer, e);\n        n && (t.labels = n), this.Ho(t);\n    }\n    /**\n     * Unregisters interest in the results of the target associated with the\n     * given targetId.\n     */    s_(e) {\n        const t = {};\n        t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.removeTarget = e, \n        this.Ho(t);\n    }\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */ class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream {\n    constructor(e, t, n, r, i, s) {\n        super(e, \"write_stream_connection_backoff\" /* TimerId.WriteStreamConnectionBackoff */ , \"write_stream_idle\" /* TimerId.WriteStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , t, n, r, s), \n        this.serializer = i, this.o_ = !1;\n    }\n    /**\n     * Tracks whether or not a handshake has been successfully exchanged and\n     * the stream is ready to accept mutations.\n     */    get __() {\n        return this.o_;\n    }\n    // Override of PersistentStream.start\n    start() {\n        this.o_ = !1, this.lastStreamToken = void 0, super.start();\n    }\n    Zo() {\n        this.o_ && this.a_([]);\n    }\n    n_(e, t) {\n        return this.connection.wo(\"Write\", e, t);\n    }\n    onMessage(e) {\n        if (\n        // Always capture the last stream token.\n        __PRIVATE_hardAssert(!!e.streamToken), this.lastStreamToken = e.streamToken, this.o_) {\n            // A successful first write response means the stream is healthy,\n            // Note, that we could consider a successful handshake healthy, however,\n            // the write itself might be causing an error we want to back off from.\n            this.Ko.reset();\n            const t = __PRIVATE_fromWriteResults(e.writeResults, e.commitTime), n = __PRIVATE_fromVersion(e.commitTime);\n            return this.listener.u_(n, t);\n        }\n        // The first response is always the handshake response\n        return __PRIVATE_hardAssert(!e.writeResults || 0 === e.writeResults.length), this.o_ = !0, \n        this.listener.c_();\n    }\n    /**\n     * Sends an initial streamToken to the server, performing the handshake\n     * required to make the StreamingWrite RPC work. Subsequent\n     * calls should wait until onHandshakeComplete was called.\n     */    l_() {\n        // TODO(dimond): Support stream resumption. We intentionally do not set the\n        // stream token on the handshake, ignoring any stream token we might have.\n        const e = {};\n        e.database = __PRIVATE_getEncodedDatabaseId(this.serializer), this.Ho(e);\n    }\n    /** Sends a group of mutations to the Firestore backend to apply. */    a_(e) {\n        const t = {\n            streamToken: this.lastStreamToken,\n            writes: e.map((e => toMutation(this.serializer, e)))\n        };\n        this.Ho(t);\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass __PRIVATE_DatastoreImpl extends class Datastore {} {\n    constructor(e, t, n, r) {\n        super(), this.authCredentials = e, this.appCheckCredentials = t, this.connection = n, \n        this.serializer = r, this.h_ = !1;\n    }\n    P_() {\n        if (this.h_) throw new FirestoreError(v.FAILED_PRECONDITION, \"The client has already been terminated.\");\n    }\n    /** Invokes the provided RPC with auth and AppCheck tokens. */    Vo(e, t, n) {\n        return this.P_(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([r, i]) => this.connection.Vo(e, t, n, r, i))).catch((e => {\n            throw \"FirebaseError\" === e.name ? (e.code === v.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n            this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(v.UNKNOWN, e.toString());\n        }));\n    }\n    /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */    yo(e, t, n, r) {\n        return this.P_(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.yo(e, t, n, i, s, r))).catch((e => {\n            throw \"FirebaseError\" === e.name ? (e.code === v.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n            this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(v.UNKNOWN, e.toString());\n        }));\n    }\n    terminate() {\n        this.h_ = !0;\n    }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nasync function __PRIVATE_invokeRunAggregationQueryRpc(e, t, n) {\n    var r;\n    const i = __PRIVATE_debugCast(e), {request: s, I_: o} = function __PRIVATE_toRunAggregationQueryRequest(e, t, n) {\n        const r = __PRIVATE_toQueryTarget(e, t), i = {}, s = [];\n        let o = 0;\n        return n.forEach((e => {\n            // Map all client-side aliases to a unique short-form\n            // alias. This avoids issues with client-side aliases that\n            // exceed the 1500-byte string size limit.\n            const t = \"aggregate_\" + o++;\n            i[t] = e.alias, \"count\" === e.Ee ? s.push({\n                alias: t,\n                count: {}\n            }) : \"avg\" === e.Ee ? s.push({\n                alias: t,\n                avg: {\n                    field: __PRIVATE_toFieldPathReference(e.fieldPath)\n                }\n            }) : \"sum\" === e.Ee && s.push({\n                alias: t,\n                sum: {\n                    field: __PRIVATE_toFieldPathReference(e.fieldPath)\n                }\n            });\n        })), {\n            request: {\n                structuredAggregationQuery: {\n                    aggregations: s,\n                    structuredQuery: r.structuredQuery\n                },\n                parent: r.parent\n            },\n            I_: i\n        };\n    }(i.serializer, __PRIVATE_queryToTarget(t), n), _ = s.parent;\n    i.connection.Ro || delete s.parent;\n    const a = (await i.yo(\"RunAggregationQuery\", _, s, /*expectedResponseCount=*/ 1)).filter((e => !!e.result));\n    // Omit RunAggregationQueryResponse that only contain readTimes.\n        __PRIVATE_hardAssert(1 === a.length);\n    // Remap the short-form aliases that were sent to the server\n    // to the client-side aliases. Users will access the results\n    // using the client-side alias.\n    const u = null === (r = a[0].result) || void 0 === r ? void 0 : r.aggregateFields;\n    return Object.keys(u).reduce(((e, t) => (e[o[t]] = u[t], e)), {});\n}\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nclass __PRIVATE_OnlineStateTracker {\n    constructor(e, t) {\n        this.asyncQueue = e, this.onlineStateHandler = t, \n        /** The current OnlineState. */\n        this.state = \"Unknown\" /* OnlineState.Unknown */ , \n        /**\n         * A count of consecutive failures to open the stream. If it reaches the\n         * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n         * Offline.\n         */\n        this.T_ = 0, \n        /**\n         * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n         * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n         * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n         */\n        this.E_ = null, \n        /**\n         * Whether the client should log a warning message if it fails to connect to\n         * the backend (initially true, cleared after a successful stream, or if we've\n         * logged the message already).\n         */\n        this.d_ = !0;\n    }\n    /**\n     * Called by RemoteStore when a watch stream is started (including on each\n     * backoff attempt).\n     *\n     * If this is the first attempt, it sets the OnlineState to Unknown and starts\n     * the onlineStateTimer.\n     */    A_() {\n        0 === this.T_ && (this.R_(\"Unknown\" /* OnlineState.Unknown */), this.E_ = this.asyncQueue.enqueueAfterDelay(\"online_state_timeout\" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this.E_ = null, \n        this.V_(\"Backend didn't respond within 10 seconds.\"), this.R_(\"Offline\" /* OnlineState.Offline */), \n        Promise.resolve()))));\n    }\n    /**\n     * Updates our OnlineState as appropriate after the watch stream reports a\n     * failure. The first failure moves us to the 'Unknown' state. We then may\n     * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n     * actually transition to the 'Offline' state.\n     */    m_(e) {\n        \"Online\" /* OnlineState.Online */ === this.state ? this.R_(\"Unknown\" /* OnlineState.Unknown */) : (this.T_++, \n        this.T_ >= 1 && (this.f_(), this.V_(`Connection failed 1 times. Most recent error: ${e.toString()}`), \n        this.R_(\"Offline\" /* OnlineState.Offline */)));\n    }\n    /**\n     * Explicitly sets the OnlineState to the specified state.\n     *\n     * Note that this resets our timers / failure counters, etc. used by our\n     * Offline heuristics, so must not be used in place of\n     * handleWatchStreamStart() and handleWatchStreamFailure().\n     */    set(e) {\n        this.f_(), this.T_ = 0, \"Online\" /* OnlineState.Online */ === e && (\n        // We've connected to watch at least once. Don't warn the developer\n        // about being offline going forward.\n        this.d_ = !1), this.R_(e);\n    }\n    R_(e) {\n        e !== this.state && (this.state = e, this.onlineStateHandler(e));\n    }\n    V_(e) {\n        const t = `Could not reach Cloud Firestore backend. ${e}\\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;\n        this.d_ ? (__PRIVATE_logError(t), this.d_ = !1) : __PRIVATE_logDebug(\"OnlineStateTracker\", t);\n    }\n    f_() {\n        null !== this.E_ && (this.E_.cancel(), this.E_ = null);\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_RemoteStoreImpl {\n    constructor(\n    /**\n     * The local store, used to fill the write pipeline with outbound mutations.\n     */\n    e, \n    /** The client-side proxy for interacting with the backend. */\n    t, n, r, i) {\n        this.localStore = e, this.datastore = t, this.asyncQueue = n, this.remoteSyncer = {}, \n        /**\n         * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n         * LocalStore via fillWritePipeline() and have or will send to the write\n         * stream.\n         *\n         * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n         * restart the write stream. When the stream is established the writes in the\n         * pipeline will be sent in order.\n         *\n         * Writes remain in writePipeline until they are acknowledged by the backend\n         * and thus will automatically be re-sent if the stream is interrupted /\n         * restarted before they're acknowledged.\n         *\n         * Write responses from the backend are linked to their originating request\n         * purely based on order, and so we can just shift() writes from the front of\n         * the writePipeline as we receive responses.\n         */\n        this.g_ = [], \n        /**\n         * A mapping of watched targets that the client cares about tracking and the\n         * user has explicitly called a 'listen' for this target.\n         *\n         * These targets may or may not have been sent to or acknowledged by the\n         * server. On re-establishing the listen stream, these targets should be sent\n         * to the server. The targets removed with unlistens are removed eagerly\n         * without waiting for confirmation from the listen stream.\n         */\n        this.p_ = new Map, \n        /**\n         * A set of reasons for why the RemoteStore may be offline. If empty, the\n         * RemoteStore may start its network connections.\n         */\n        this.y_ = new Set, \n        /**\n         * Event handlers that get called when the network is disabled or enabled.\n         *\n         * PORTING NOTE: These functions are used on the Web client to create the\n         * underlying streams (to support tree-shakeable streams). On Android and iOS,\n         * the streams are created during construction of RemoteStore.\n         */\n        this.w_ = [], this.S_ = i, this.S_.Ys((e => {\n            n.enqueueAndForget((async () => {\n                // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n                // network becomes unreachable as we don't have any other way to tear\n                // down our streams.\n                __PRIVATE_canUseNetwork(this) && (__PRIVATE_logDebug(\"RemoteStore\", \"Restarting streams for network reachability change.\"), \n                await async function __PRIVATE_restartNetwork(e) {\n                    const t = __PRIVATE_debugCast(e);\n                    t.y_.add(4 /* OfflineCause.ConnectivityChange */), await __PRIVATE_disableNetworkInternal(t), \n                    t.b_.set(\"Unknown\" /* OnlineState.Unknown */), t.y_.delete(4 /* OfflineCause.ConnectivityChange */), \n                    await __PRIVATE_enableNetworkInternal(t);\n                }(this));\n            }));\n        })), this.b_ = new __PRIVATE_OnlineStateTracker(n, r);\n    }\n}\n\nasync function __PRIVATE_enableNetworkInternal(e) {\n    if (__PRIVATE_canUseNetwork(e)) for (const t of e.w_) await t(/* enabled= */ !0);\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */ async function __PRIVATE_disableNetworkInternal(e) {\n    for (const t of e.w_) await t(/* enabled= */ !1);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nfunction __PRIVATE_remoteStoreListen(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    n.p_.has(t.targetId) || (\n    // Mark this as something the client is currently listening for.\n    n.p_.set(t.targetId, t), __PRIVATE_shouldStartWatchStream(n) ? \n    // The listen will be sent in onWatchStreamOpen\n    __PRIVATE_startWatchStream(n) : __PRIVATE_ensureWatchStream(n).Uo() && __PRIVATE_sendWatchRequest(n, t));\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */ function __PRIVATE_remoteStoreUnlisten(e, t) {\n    const n = __PRIVATE_debugCast(e), r = __PRIVATE_ensureWatchStream(n);\n    n.p_.delete(t), r.Uo() && __PRIVATE_sendUnwatchRequest(n, t), 0 === n.p_.size && (r.Uo() ? r.zo() : __PRIVATE_canUseNetwork(n) && \n    // Revert to OnlineState.Unknown if the watch stream is not open and we\n    // have no listeners, since without any listens to send we cannot\n    // confirm if the stream is healthy and upgrade to OnlineState.Online.\n    n.b_.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */ function __PRIVATE_sendWatchRequest(e, t) {\n    if (e.D_.Be(t.targetId), t.resumeToken.approximateByteSize() > 0 || t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n        const n = e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;\n        t = t.withExpectedCount(n);\n    }\n    __PRIVATE_ensureWatchStream(e).i_(t);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */ function __PRIVATE_sendUnwatchRequest(e, t) {\n    e.D_.Be(t), __PRIVATE_ensureWatchStream(e).s_(t);\n}\n\nfunction __PRIVATE_startWatchStream(e) {\n    e.D_ = new __PRIVATE_WatchChangeAggregator({\n        getRemoteKeysForTarget: t => e.remoteSyncer.getRemoteKeysForTarget(t),\n        ut: t => e.p_.get(t) || null,\n        rt: () => e.datastore.serializer.databaseId\n    }), __PRIVATE_ensureWatchStream(e).start(), e.b_.A_();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */ function __PRIVATE_shouldStartWatchStream(e) {\n    return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWatchStream(e).$o() && e.p_.size > 0;\n}\n\nfunction __PRIVATE_canUseNetwork(e) {\n    return 0 === __PRIVATE_debugCast(e).y_.size;\n}\n\nfunction __PRIVATE_cleanUpWatchStreamState(e) {\n    e.D_ = void 0;\n}\n\nasync function __PRIVATE_onWatchStreamOpen(e) {\n    e.p_.forEach(((t, n) => {\n        __PRIVATE_sendWatchRequest(e, t);\n    }));\n}\n\nasync function __PRIVATE_onWatchStreamClose(e, t) {\n    __PRIVATE_cleanUpWatchStreamState(e), \n    // If we still need the watch stream, retry the connection.\n    __PRIVATE_shouldStartWatchStream(e) ? (e.b_.m_(t), __PRIVATE_startWatchStream(e)) : \n    // No need to restart watch stream because there are no active targets.\n    // The online state is set to unknown because there is no active attempt\n    // at establishing a connection\n    e.b_.set(\"Unknown\" /* OnlineState.Unknown */);\n}\n\nasync function __PRIVATE_onWatchStreamChange(e, t, n) {\n    if (\n    // Mark the client as online since we got a message from the server\n    e.b_.set(\"Online\" /* OnlineState.Online */), t instanceof __PRIVATE_WatchTargetChange && 2 /* WatchTargetChangeState.Removed */ === t.state && t.cause) \n    // There was an error on a target, don't wait for a consistent snapshot\n    // to raise events\n    try {\n        await \n        /** Handles an error on a target */\n        async function __PRIVATE_handleTargetError(e, t) {\n            const n = t.cause;\n            for (const r of t.targetIds) \n            // A watched target might have been removed already.\n            e.p_.has(r) && (await e.remoteSyncer.rejectListen(r, n), e.p_.delete(r), e.D_.removeTarget(r));\n        }\n        /**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */ (e, t);\n    } catch (n) {\n        __PRIVATE_logDebug(\"RemoteStore\", \"Failed to remove targets %s: %s \", t.targetIds.join(\",\"), n), \n        await __PRIVATE_disableNetworkUntilRecovery(e, n);\n    } else if (t instanceof __PRIVATE_DocumentWatchChange ? e.D_.We(t) : t instanceof __PRIVATE_ExistenceFilterChange ? e.D_.Ze(t) : e.D_.je(t), \n    !n.isEqual(SnapshotVersion.min())) try {\n        const t = await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore);\n        n.compareTo(t) >= 0 && \n        // We have received a target change with a global snapshot if the snapshot\n        // version is not equal to SnapshotVersion.min().\n        await \n        /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n        function __PRIVATE_raiseWatchSnapshot(e, t) {\n            const n = e.D_.st(t);\n            // Update in-memory resume tokens. LocalStore will update the\n            // persistent view of these when applying the completed RemoteEvent.\n                        return n.targetChanges.forEach(((n, r) => {\n                if (n.resumeToken.approximateByteSize() > 0) {\n                    const i = e.p_.get(r);\n                    // A watched target might have been removed already.\n                                        i && e.p_.set(r, i.withResumeToken(n.resumeToken, t));\n                }\n            })), \n            // Re-establish listens for the targets that have been invalidated by\n            // existence filter mismatches.\n            n.targetMismatches.forEach(((t, n) => {\n                const r = e.p_.get(t);\n                if (!r) \n                // A watched target might have been removed already.\n                return;\n                // Clear the resume token for the target, since we're in a known mismatch\n                // state.\n                                e.p_.set(t, r.withResumeToken(ByteString.EMPTY_BYTE_STRING, r.snapshotVersion)), \n                // Cause a hard reset by unwatching and rewatching immediately, but\n                // deliberately don't send a resume token so that we get a full update.\n                __PRIVATE_sendUnwatchRequest(e, t);\n                // Mark the target we send as being on behalf of an existence filter\n                // mismatch, but don't actually retain that in listenTargets. This ensures\n                // that we flag the first re-listen this way without impacting future\n                // listens of this target (that might happen e.g. on reconnect).\n                const i = new TargetData(r.target, t, n, r.sequenceNumber);\n                __PRIVATE_sendWatchRequest(e, i);\n            })), e.remoteSyncer.applyRemoteEvent(n);\n        }(e, n);\n    } catch (t) {\n        __PRIVATE_logDebug(\"RemoteStore\", \"Failed to raise snapshot:\", t), await __PRIVATE_disableNetworkUntilRecovery(e, t);\n    }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */ async function __PRIVATE_disableNetworkUntilRecovery(e, t, n) {\n    if (!__PRIVATE_isIndexedDbTransactionError(t)) throw t;\n    e.y_.add(1 /* OfflineCause.IndexedDbFailed */), \n    // Disable network and raise offline snapshots\n    await __PRIVATE_disableNetworkInternal(e), e.b_.set(\"Offline\" /* OnlineState.Offline */), \n    n || (\n    // Use a simple read operation to determine if IndexedDB recovered.\n    // Ideally, we would expose a health check directly on SimpleDb, but\n    // RemoteStore only has access to persistence through LocalStore.\n    n = () => __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)), \n    // Probe IndexedDB periodically and re-enable network\n    e.asyncQueue.enqueueRetryable((async () => {\n        __PRIVATE_logDebug(\"RemoteStore\", \"Retrying IndexedDB access\"), await n(), e.y_.delete(1 /* OfflineCause.IndexedDbFailed */), \n        await __PRIVATE_enableNetworkInternal(e);\n    }));\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */ function __PRIVATE_executeWithRecovery(e, t) {\n    return t().catch((n => __PRIVATE_disableNetworkUntilRecovery(e, n, t)));\n}\n\nasync function __PRIVATE_fillWritePipeline(e) {\n    const t = __PRIVATE_debugCast(e), n = __PRIVATE_ensureWriteStream(t);\n    let r = t.g_.length > 0 ? t.g_[t.g_.length - 1].batchId : -1;\n    for (;__PRIVATE_canAddToWritePipeline(t); ) try {\n        const e = await __PRIVATE_localStoreGetNextMutationBatch(t.localStore, r);\n        if (null === e) {\n            0 === t.g_.length && n.zo();\n            break;\n        }\n        r = e.batchId, __PRIVATE_addToWritePipeline(t, e);\n    } catch (e) {\n        await __PRIVATE_disableNetworkUntilRecovery(t, e);\n    }\n    __PRIVATE_shouldStartWriteStream(t) && __PRIVATE_startWriteStream(t);\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */ function __PRIVATE_canAddToWritePipeline(e) {\n    return __PRIVATE_canUseNetwork(e) && e.g_.length < 10;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */ function __PRIVATE_addToWritePipeline(e, t) {\n    e.g_.push(t);\n    const n = __PRIVATE_ensureWriteStream(e);\n    n.Uo() && n.__ && n.a_(t.mutations);\n}\n\nfunction __PRIVATE_shouldStartWriteStream(e) {\n    return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWriteStream(e).$o() && e.g_.length > 0;\n}\n\nfunction __PRIVATE_startWriteStream(e) {\n    __PRIVATE_ensureWriteStream(e).start();\n}\n\nasync function __PRIVATE_onWriteStreamOpen(e) {\n    __PRIVATE_ensureWriteStream(e).l_();\n}\n\nasync function __PRIVATE_onWriteHandshakeComplete(e) {\n    const t = __PRIVATE_ensureWriteStream(e);\n    // Send the write pipeline now that the stream is established.\n        for (const n of e.g_) t.a_(n.mutations);\n}\n\nasync function __PRIVATE_onMutationResult(e, t, n) {\n    const r = e.g_.shift(), i = MutationBatchResult.from(r, t, n);\n    await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.applySuccessfulWrite(i))), \n    // It's possible that with the completion of this mutation another\n    // slot has freed up.\n    await __PRIVATE_fillWritePipeline(e);\n}\n\nasync function __PRIVATE_onWriteStreamClose(e, t) {\n    // If the write stream closed after the write handshake completes, a write\n    // operation failed and we fail the pending operation.\n    t && __PRIVATE_ensureWriteStream(e).__ && \n    // This error affects the actual write.\n    await async function __PRIVATE_handleWriteError(e, t) {\n        // Only handle permanent errors here. If it's transient, just let the retry\n        // logic kick in.\n        if (function __PRIVATE_isPermanentWriteError(e) {\n            return __PRIVATE_isPermanentError(e) && e !== v.ABORTED;\n        }(t.code)) {\n            // This was a permanent error, the request itself was the problem\n            // so it's not going to succeed if we resend it.\n            const n = e.g_.shift();\n            // In this case it's also unlikely that the server itself is melting\n            // down -- this was just a bad request so inhibit backoff on the next\n            // restart.\n                        __PRIVATE_ensureWriteStream(e).Go(), await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.rejectFailedWrite(n.batchId, t))), \n            // It's possible that with the completion of this mutation\n            // another slot has freed up.\n            await __PRIVATE_fillWritePipeline(e);\n        }\n    }(e, t), \n    // The write stream might have been started by refilling the write\n    // pipeline for failed writes\n    __PRIVATE_shouldStartWriteStream(e) && __PRIVATE_startWriteStream(e);\n}\n\nasync function __PRIVATE_remoteStoreHandleCredentialChange(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    n.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(\"RemoteStore\", \"RemoteStore received new credentials\");\n    const r = __PRIVATE_canUseNetwork(n);\n    // Tear down and re-create our network streams. This will ensure we get a\n    // fresh auth token for the new user and re-fill the write pipeline with\n    // new mutations from the LocalStore (since mutations are per-user).\n        n.y_.add(3 /* OfflineCause.CredentialChange */), await __PRIVATE_disableNetworkInternal(n), \n    r && \n    // Don't set the network status to Unknown if we are offline.\n    n.b_.set(\"Unknown\" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(t), \n    n.y_.delete(3 /* OfflineCause.CredentialChange */), await __PRIVATE_enableNetworkInternal(n);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */ async function __PRIVATE_remoteStoreApplyPrimaryState(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    t ? (n.y_.delete(2 /* OfflineCause.IsSecondary */), await __PRIVATE_enableNetworkInternal(n)) : t || (n.y_.add(2 /* OfflineCause.IsSecondary */), \n    await __PRIVATE_disableNetworkInternal(n), n.b_.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function __PRIVATE_ensureWatchStream(e) {\n    return e.v_ || (\n    // Create stream (but note that it is not started yet).\n    e.v_ = function __PRIVATE_newPersistentWatchStream(e, t, n) {\n        const r = __PRIVATE_debugCast(e);\n        return r.P_(), new __PRIVATE_PersistentListenStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);\n    }\n    /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (e.datastore, e.asyncQueue, {\n        _o: __PRIVATE_onWatchStreamOpen.bind(null, e),\n        uo: __PRIVATE_onWatchStreamClose.bind(null, e),\n        r_: __PRIVATE_onWatchStreamChange.bind(null, e)\n    }), e.w_.push((async t => {\n        t ? (e.v_.Go(), __PRIVATE_shouldStartWatchStream(e) ? __PRIVATE_startWatchStream(e) : e.b_.set(\"Unknown\" /* OnlineState.Unknown */)) : (await e.v_.stop(), \n        __PRIVATE_cleanUpWatchStreamState(e));\n    }))), e.v_;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function __PRIVATE_ensureWriteStream(e) {\n    return e.C_ || (\n    // Create stream (but note that it is not started yet).\n    e.C_ = function __PRIVATE_newPersistentWriteStream(e, t, n) {\n        const r = __PRIVATE_debugCast(e);\n        return r.P_(), new __PRIVATE_PersistentWriteStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);\n    }(e.datastore, e.asyncQueue, {\n        _o: __PRIVATE_onWriteStreamOpen.bind(null, e),\n        uo: __PRIVATE_onWriteStreamClose.bind(null, e),\n        c_: __PRIVATE_onWriteHandshakeComplete.bind(null, e),\n        u_: __PRIVATE_onMutationResult.bind(null, e)\n    }), e.w_.push((async t => {\n        t ? (e.C_.Go(), \n        // This will start the write stream if necessary.\n        await __PRIVATE_fillWritePipeline(e)) : (await e.C_.stop(), e.g_.length > 0 && (__PRIVATE_logDebug(\"RemoteStore\", `Stopping write stream with ${e.g_.length} pending writes`), \n        e.g_ = []));\n    }))), e.C_;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nclass DelayedOperation {\n    constructor(e, t, n, r, i) {\n        this.asyncQueue = e, this.timerId = t, this.targetTimeMs = n, this.op = r, this.removalCallback = i, \n        this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), \n        // It's normal for the deferred promise to be canceled (due to cancellation)\n        // and so we attach a dummy catch callback to avoid\n        // 'UnhandledPromiseRejectionWarning' log spam.\n        this.deferred.promise.catch((e => {}));\n    }\n    /**\n     * Creates and returns a DelayedOperation that has been scheduled to be\n     * executed on the provided asyncQueue after the provided delayMs.\n     *\n     * @param asyncQueue - The queue to schedule the operation on.\n     * @param id - A Timer ID identifying the type of operation this is.\n     * @param delayMs - The delay (ms) before the operation should be scheduled.\n     * @param op - The operation to run.\n     * @param removalCallback - A callback to be called synchronously once the\n     *   operation is executed or canceled, notifying the AsyncQueue to remove it\n     *   from its delayedOperations list.\n     *   PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n     *   the DelayedOperation class public.\n     */    static createAndSchedule(e, t, n, r, i) {\n        const s = Date.now() + n, o = new DelayedOperation(e, t, s, r, i);\n        return o.start(n), o;\n    }\n    /**\n     * Starts the timer. This is called immediately after construction by\n     * createAndSchedule().\n     */    start(e) {\n        this.timerHandle = setTimeout((() => this.handleDelayElapsed()), e);\n    }\n    /**\n     * Queues the operation to run immediately (if it hasn't already been run or\n     * canceled).\n     */    skipDelay() {\n        return this.handleDelayElapsed();\n    }\n    /**\n     * Cancels the operation if it hasn't already been executed or canceled. The\n     * promise will be rejected.\n     *\n     * As long as the operation has not yet been run, calling cancel() provides a\n     * guarantee that the operation will not be run.\n     */    cancel(e) {\n        null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(v.CANCELLED, \"Operation cancelled\" + (e ? \": \" + e : \"\"))));\n    }\n    handleDelayElapsed() {\n        this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), \n        this.op().then((e => this.deferred.resolve(e)))) : Promise.resolve()));\n    }\n    clearTimeout() {\n        null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), \n        this.timerHandle = null);\n    }\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */ function __PRIVATE_wrapInUserErrorIfRecoverable(e, t) {\n    if (__PRIVATE_logError(\"AsyncQueue\", `${t}: ${e}`), __PRIVATE_isIndexedDbTransactionError(e)) return new FirestoreError(v.UNAVAILABLE, `${t}: ${e}`);\n    throw e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */ class DocumentSet {\n    /** The default ordering is by key if the comparator is omitted */\n    constructor(e) {\n        // We are adding document key comparator to the end as it's the only\n        // guaranteed unique property of a document.\n        this.comparator = e ? (t, n) => e(t, n) || DocumentKey.comparator(t.key, n.key) : (e, t) => DocumentKey.comparator(e.key, t.key), \n        this.keyedMap = documentMap(), this.sortedSet = new SortedMap(this.comparator);\n    }\n    /**\n     * Returns an empty copy of the existing DocumentSet, using the same\n     * comparator.\n     */    static emptySet(e) {\n        return new DocumentSet(e.comparator);\n    }\n    has(e) {\n        return null != this.keyedMap.get(e);\n    }\n    get(e) {\n        return this.keyedMap.get(e);\n    }\n    first() {\n        return this.sortedSet.minKey();\n    }\n    last() {\n        return this.sortedSet.maxKey();\n    }\n    isEmpty() {\n        return this.sortedSet.isEmpty();\n    }\n    /**\n     * Returns the index of the provided key in the document set, or -1 if the\n     * document key is not present in the set;\n     */    indexOf(e) {\n        const t = this.keyedMap.get(e);\n        return t ? this.sortedSet.indexOf(t) : -1;\n    }\n    get size() {\n        return this.sortedSet.size;\n    }\n    /** Iterates documents in order defined by \"comparator\" */    forEach(e) {\n        this.sortedSet.inorderTraversal(((t, n) => (e(t), !1)));\n    }\n    /** Inserts or updates a document with the same key */    add(e) {\n        // First remove the element if we have it.\n        const t = this.delete(e.key);\n        return t.copy(t.keyedMap.insert(e.key, e), t.sortedSet.insert(e, null));\n    }\n    /** Deletes a document with a given key */    delete(e) {\n        const t = this.get(e);\n        return t ? this.copy(this.keyedMap.remove(e), this.sortedSet.remove(t)) : this;\n    }\n    isEqual(e) {\n        if (!(e instanceof DocumentSet)) return !1;\n        if (this.size !== e.size) return !1;\n        const t = this.sortedSet.getIterator(), n = e.sortedSet.getIterator();\n        for (;t.hasNext(); ) {\n            const e = t.getNext().key, r = n.getNext().key;\n            if (!e.isEqual(r)) return !1;\n        }\n        return !0;\n    }\n    toString() {\n        const e = [];\n        return this.forEach((t => {\n            e.push(t.toString());\n        })), 0 === e.length ? \"DocumentSet ()\" : \"DocumentSet (\\n  \" + e.join(\"  \\n\") + \"\\n)\";\n    }\n    copy(e, t) {\n        const n = new DocumentSet;\n        return n.comparator = this.comparator, n.keyedMap = e, n.sortedSet = t, n;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */ class __PRIVATE_DocumentChangeSet {\n    constructor() {\n        this.F_ = new SortedMap(DocumentKey.comparator);\n    }\n    track(e) {\n        const t = e.doc.key, n = this.F_.get(t);\n        n ? \n        // Merge the new change with the existing change.\n        0 /* ChangeType.Added */ !== e.type && 3 /* ChangeType.Metadata */ === n.type ? this.F_ = this.F_.insert(t, e) : 3 /* ChangeType.Metadata */ === e.type && 1 /* ChangeType.Removed */ !== n.type ? this.F_ = this.F_.insert(t, {\n            type: n.type,\n            doc: e.doc\n        }) : 2 /* ChangeType.Modified */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.F_ = this.F_.insert(t, {\n            type: 2 /* ChangeType.Modified */ ,\n            doc: e.doc\n        }) : 2 /* ChangeType.Modified */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.F_ = this.F_.insert(t, {\n            type: 0 /* ChangeType.Added */ ,\n            doc: e.doc\n        }) : 1 /* ChangeType.Removed */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.F_ = this.F_.remove(t) : 1 /* ChangeType.Removed */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.F_ = this.F_.insert(t, {\n            type: 1 /* ChangeType.Removed */ ,\n            doc: n.doc\n        }) : 0 /* ChangeType.Added */ === e.type && 1 /* ChangeType.Removed */ === n.type ? this.F_ = this.F_.insert(t, {\n            type: 2 /* ChangeType.Modified */ ,\n            doc: e.doc\n        }) : \n        // This includes these cases, which don't make sense:\n        // Added->Added\n        // Removed->Removed\n        // Modified->Added\n        // Removed->Modified\n        // Metadata->Added\n        // Removed->Metadata\n        fail() : this.F_ = this.F_.insert(t, e);\n    }\n    M_() {\n        const e = [];\n        return this.F_.inorderTraversal(((t, n) => {\n            e.push(n);\n        })), e;\n    }\n}\n\nclass ViewSnapshot {\n    constructor(e, t, n, r, i, s, o, _, a) {\n        this.query = e, this.docs = t, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i, \n        this.fromCache = s, this.syncStateChanged = o, this.excludesMetadataChanges = _, \n        this.hasCachedResults = a;\n    }\n    /** Returns a view snapshot as if all documents in the snapshot were added. */    static fromInitialDocuments(e, t, n, r, i) {\n        const s = [];\n        return t.forEach((e => {\n            s.push({\n                type: 0 /* ChangeType.Added */ ,\n                doc: e\n            });\n        })), new ViewSnapshot(e, t, DocumentSet.emptySet(t), s, n, r, \n        /* syncStateChanged= */ !0, \n        /* excludesMetadataChanges= */ !1, i);\n    }\n    get hasPendingWrites() {\n        return !this.mutatedKeys.isEmpty();\n    }\n    isEqual(e) {\n        if (!(this.fromCache === e.fromCache && this.hasCachedResults === e.hasCachedResults && this.syncStateChanged === e.syncStateChanged && this.mutatedKeys.isEqual(e.mutatedKeys) && __PRIVATE_queryEquals(this.query, e.query) && this.docs.isEqual(e.docs) && this.oldDocs.isEqual(e.oldDocs))) return !1;\n        const t = this.docChanges, n = e.docChanges;\n        if (t.length !== n.length) return !1;\n        for (let e = 0; e < t.length; e++) if (t[e].type !== n[e].type || !t[e].doc.isEqual(n[e].doc)) return !1;\n        return !0;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */ class __PRIVATE_QueryListenersInfo {\n    constructor() {\n        this.x_ = void 0, this.listeners = [];\n    }\n}\n\nclass __PRIVATE_EventManagerImpl {\n    constructor() {\n        this.queries = new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals), \n        this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , this.O_ = new Set;\n    }\n}\n\nasync function __PRIVATE_eventManagerListen(e, t) {\n    const n = __PRIVATE_debugCast(e), r = t.query;\n    let i = !1, s = n.queries.get(r);\n    if (s || (i = !0, s = new __PRIVATE_QueryListenersInfo), i) try {\n        s.x_ = await n.onListen(r);\n    } catch (e) {\n        const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Initialization of query '${__PRIVATE_stringifyQuery(t.query)}' failed`);\n        return void t.onError(n);\n    }\n    if (n.queries.set(r, s), s.listeners.push(t), \n    // Run global snapshot listeners if a consistent snapshot has been emitted.\n    t.N_(n.onlineState), s.x_) {\n        t.B_(s.x_) && __PRIVATE_raiseSnapshotsInSyncEvent(n);\n    }\n}\n\nasync function __PRIVATE_eventManagerUnlisten(e, t) {\n    const n = __PRIVATE_debugCast(e), r = t.query;\n    let i = !1;\n    const s = n.queries.get(r);\n    if (s) {\n        const e = s.listeners.indexOf(t);\n        e >= 0 && (s.listeners.splice(e, 1), i = 0 === s.listeners.length);\n    }\n    if (i) return n.queries.delete(r), n.onUnlisten(r);\n}\n\nfunction __PRIVATE_eventManagerOnWatchChange(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    let r = !1;\n    for (const e of t) {\n        const t = e.query, i = n.queries.get(t);\n        if (i) {\n            for (const t of i.listeners) t.B_(e) && (r = !0);\n            i.x_ = e;\n        }\n    }\n    r && __PRIVATE_raiseSnapshotsInSyncEvent(n);\n}\n\nfunction __PRIVATE_eventManagerOnWatchError(e, t, n) {\n    const r = __PRIVATE_debugCast(e), i = r.queries.get(t);\n    if (i) for (const e of i.listeners) e.onError(n);\n    // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n    // after an error.\n        r.queries.delete(t);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction __PRIVATE_raiseSnapshotsInSyncEvent(e) {\n    e.O_.forEach((e => {\n        e.next();\n    }));\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */ class __PRIVATE_QueryListener {\n    constructor(e, t, n) {\n        this.query = e, this.L_ = t, \n        /**\n         * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n         * observer. This flag is set to true once we've actually raised an event.\n         */\n        this.k_ = !1, this.q_ = null, this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n        this.options = n || {};\n    }\n    /**\n     * Applies the new ViewSnapshot to this listener, raising a user-facing event\n     * if applicable (depending on what changed, whether the user has opted into\n     * metadata-only changes, etc.). Returns true if a user-facing event was\n     * indeed raised.\n     */    B_(e) {\n        if (!this.options.includeMetadataChanges) {\n            // Remove the metadata only changes.\n            const t = [];\n            for (const n of e.docChanges) 3 /* ChangeType.Metadata */ !== n.type && t.push(n);\n            e = new ViewSnapshot(e.query, e.docs, e.oldDocs, t, e.mutatedKeys, e.fromCache, e.syncStateChanged, \n            /* excludesMetadataChanges= */ !0, e.hasCachedResults);\n        }\n        let t = !1;\n        return this.k_ ? this.Q_(e) && (this.L_.next(e), t = !0) : this.K_(e, this.onlineState) && (this.U_(e), \n        t = !0), this.q_ = e, t;\n    }\n    onError(e) {\n        this.L_.error(e);\n    }\n    /** Returns whether a snapshot was raised. */    N_(e) {\n        this.onlineState = e;\n        let t = !1;\n        return this.q_ && !this.k_ && this.K_(this.q_, e) && (this.U_(this.q_), t = !0), \n        t;\n    }\n    K_(e, t) {\n        // Always raise the first event when we're synced\n        if (!e.fromCache) return !0;\n        // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n        // or Online if we wait long enough).\n                const n = \"Offline\" /* OnlineState.Offline */ !== t;\n        // Don't raise the event if we're online, aren't synced yet (checked\n        // above) and are waiting for a sync.\n                return (!this.options.W_ || !n) && (!e.docs.isEmpty() || e.hasCachedResults || \"Offline\" /* OnlineState.Offline */ === t);\n        // Raise data from cache if we have any documents, have cached results before,\n        // or we are offline.\n        }\n    Q_(e) {\n        // We don't need to handle includeDocumentMetadataChanges here because\n        // the Metadata only changes have already been stripped out if needed.\n        // At this point the only changes we will see are the ones we should\n        // propagate.\n        if (e.docChanges.length > 0) return !0;\n        const t = this.q_ && this.q_.hasPendingWrites !== e.hasPendingWrites;\n        return !(!e.syncStateChanged && !t) && !0 === this.options.includeMetadataChanges;\n        // Generally we should have hit one of the cases above, but it's possible\n        // to get here if there were only metadata docChanges and they got\n        // stripped out.\n        }\n    U_(e) {\n        e = ViewSnapshot.fromInitialDocuments(e.query, e.docs, e.mutatedKeys, e.fromCache, e.hasCachedResults), \n        this.k_ = !0, this.L_.next(e);\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */ class __PRIVATE_SizedBundleElement {\n    constructor(e, \n    // How many bytes this element takes to store in the bundle.\n    t) {\n        this.G_ = e, this.byteLength = t;\n    }\n    z_() {\n        return \"metadata\" in this.G_;\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */ class __PRIVATE_BundleConverterImpl {\n    constructor(e) {\n        this.serializer = e;\n    }\n    os(e) {\n        return fromName(this.serializer, e);\n    }\n    /**\n     * Converts a BundleDocument to a MutableDocument.\n     */    _s(e) {\n        return e.metadata.exists ? __PRIVATE_fromDocument(this.serializer, e.document, !1) : MutableDocument.newNoDocument(this.os(e.metadata.name), this.us(e.metadata.readTime));\n    }\n    us(e) {\n        return __PRIVATE_fromVersion(e);\n    }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */ class __PRIVATE_BundleLoader {\n    constructor(e, t, n) {\n        this.j_ = e, this.localStore = t, this.serializer = n, \n        /** Batched queries to be saved into storage */\n        this.queries = [], \n        /** Batched documents to be saved into storage */\n        this.documents = [], \n        /** The collection groups affected by this bundle. */\n        this.collectionGroups = new Set, this.progress = __PRIVATE_bundleInitialProgress(e);\n    }\n    /**\n     * Adds an element from the bundle to the loader.\n     *\n     * Returns a new progress if adding the element leads to a new progress,\n     * otherwise returns null.\n     */    H_(e) {\n        this.progress.bytesLoaded += e.byteLength;\n        let t = this.progress.documentsLoaded;\n        if (e.G_.namedQuery) this.queries.push(e.G_.namedQuery); else if (e.G_.documentMetadata) {\n            this.documents.push({\n                metadata: e.G_.documentMetadata\n            }), e.G_.documentMetadata.exists || ++t;\n            const n = ResourcePath.fromString(e.G_.documentMetadata.name);\n            this.collectionGroups.add(n.get(n.length - 2));\n        } else e.G_.document && (this.documents[this.documents.length - 1].document = e.G_.document, \n        ++t);\n        return t !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = t, \n        Object.assign({}, this.progress)) : null;\n    }\n    J_(e) {\n        const t = new Map, n = new __PRIVATE_BundleConverterImpl(this.serializer);\n        for (const r of e) if (r.metadata.queries) {\n            const e = n.os(r.metadata.name);\n            for (const n of r.metadata.queries) {\n                const r = (t.get(n) || __PRIVATE_documentKeySet()).add(e);\n                t.set(n, r);\n            }\n        }\n        return t;\n    }\n    /**\n     * Update the progress to 'Success' and return the updated progress.\n     */    async complete() {\n        const e = await __PRIVATE_localStoreApplyBundledDocuments(this.localStore, new __PRIVATE_BundleConverterImpl(this.serializer), this.documents, this.j_.id), t = this.J_(this.documents);\n        for (const e of this.queries) await __PRIVATE_localStoreSaveNamedQuery(this.localStore, e, t.get(e.name));\n        return this.progress.taskState = \"Success\", {\n            progress: this.progress,\n            Y_: this.collectionGroups,\n            Z_: e\n        };\n    }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */ function __PRIVATE_bundleInitialProgress(e) {\n    return {\n        taskState: \"Running\",\n        documentsLoaded: 0,\n        bytesLoaded: 0,\n        totalDocuments: e.totalDocuments,\n        totalBytes: e.totalBytes\n    };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass __PRIVATE_AddedLimboDocument {\n    constructor(e) {\n        this.key = e;\n    }\n}\n\nclass __PRIVATE_RemovedLimboDocument {\n    constructor(e) {\n        this.key = e;\n    }\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */ class __PRIVATE_View {\n    constructor(e, \n    /** Documents included in the remote target */\n    t) {\n        this.query = e, this.X_ = t, this.ea = null, this.hasCachedResults = !1, \n        /**\n         * A flag whether the view is current with the backend. A view is considered\n         * current after it has seen the current flag from the backend and did not\n         * lose consistency within the watch stream (e.g. because of an existence\n         * filter mismatch).\n         */\n        this.current = !1, \n        /** Documents in the view but not in the remote target */\n        this.ta = __PRIVATE_documentKeySet(), \n        /** Document Keys that have local changes */\n        this.mutatedKeys = __PRIVATE_documentKeySet(), this.na = __PRIVATE_newQueryComparator(e), \n        this.ra = new DocumentSet(this.na);\n    }\n    /**\n     * The set of remote documents that the server has told us belongs to the target associated with\n     * this view.\n     */    get ia() {\n        return this.X_;\n    }\n    /**\n     * Iterates over a set of doc changes, applies the query limit, and computes\n     * what the new results should be, what the changes were, and whether we may\n     * need to go back to the local cache for more results. Does not make any\n     * changes to the view.\n     * @param docChanges - The doc changes to apply to this view.\n     * @param previousChanges - If this is being called with a refill, then start\n     *        with this set of docs and changes instead of the current view.\n     * @returns a new set of docs, changes, and refill flag.\n     */    sa(e, t) {\n        const n = t ? t.oa : new __PRIVATE_DocumentChangeSet, r = t ? t.ra : this.ra;\n        let i = t ? t.mutatedKeys : this.mutatedKeys, s = r, o = !1;\n        // Track the last doc in a (full) limit. This is necessary, because some\n        // update (a delete, or an update moving a doc past the old limit) might\n        // mean there is some other document in the local cache that either should\n        // come (1) between the old last limit doc and the new last document, in the\n        // case of updates, or (2) after the new last document, in the case of\n        // deletes. So we keep this doc at the old limit to compare the updates to.\n        // Note that this should never get used in a refill (when previousChanges is\n        // set), because there will only be adds -- no deletes or updates.\n        const _ = \"F\" /* LimitType.First */ === this.query.limitType && r.size === this.query.limit ? r.last() : null, a = \"L\" /* LimitType.Last */ === this.query.limitType && r.size === this.query.limit ? r.first() : null;\n        // Drop documents out to meet limit/limitToLast requirement.\n        if (e.inorderTraversal(((e, t) => {\n            const u = r.get(e), c = __PRIVATE_queryMatches(this.query, t) ? t : null, l = !!u && this.mutatedKeys.has(u.key), h = !!c && (c.hasLocalMutations || \n            // We only consider committed mutations for documents that were\n            // mutated during the lifetime of the view.\n            this.mutatedKeys.has(c.key) && c.hasCommittedMutations);\n            let P = !1;\n            // Calculate change\n                        if (u && c) {\n                u.data.isEqual(c.data) ? l !== h && (n.track({\n                    type: 3 /* ChangeType.Metadata */ ,\n                    doc: c\n                }), P = !0) : this._a(u, c) || (n.track({\n                    type: 2 /* ChangeType.Modified */ ,\n                    doc: c\n                }), P = !0, (_ && this.na(c, _) > 0 || a && this.na(c, a) < 0) && (\n                // This doc moved from inside the limit to outside the limit.\n                // That means there may be some other doc in the local cache\n                // that should be included instead.\n                o = !0));\n            } else !u && c ? (n.track({\n                type: 0 /* ChangeType.Added */ ,\n                doc: c\n            }), P = !0) : u && !c && (n.track({\n                type: 1 /* ChangeType.Removed */ ,\n                doc: u\n            }), P = !0, (_ || a) && (\n            // A doc was removed from a full limit query. We'll need to\n            // requery from the local cache to see if we know about some other\n            // doc that should be in the results.\n            o = !0));\n            P && (c ? (s = s.add(c), i = h ? i.add(e) : i.delete(e)) : (s = s.delete(e), i = i.delete(e)));\n        })), null !== this.query.limit) for (;s.size > this.query.limit; ) {\n            const e = \"F\" /* LimitType.First */ === this.query.limitType ? s.last() : s.first();\n            s = s.delete(e.key), i = i.delete(e.key), n.track({\n                type: 1 /* ChangeType.Removed */ ,\n                doc: e\n            });\n        }\n        return {\n            ra: s,\n            oa: n,\n            zi: o,\n            mutatedKeys: i\n        };\n    }\n    _a(e, t) {\n        // We suppress the initial change event for documents that were modified as\n        // part of a write acknowledgment (e.g. when the value of a server transform\n        // is applied) as Watch will send us the same document again.\n        // By suppressing the event, we only raise two user visible events (one with\n        // `hasPendingWrites` and the final state of the document) instead of three\n        // (one with `hasPendingWrites`, the modified document with\n        // `hasPendingWrites` and the final state of the document).\n        return e.hasLocalMutations && t.hasCommittedMutations && !t.hasLocalMutations;\n    }\n    /**\n     * Updates the view with the given ViewDocumentChanges and optionally updates\n     * limbo docs and sync state from the provided target change.\n     * @param docChanges - The set of changes to make to the view's docs.\n     * @param updateLimboDocuments - Whether to update limbo documents based on\n     *        this change.\n     * @param targetChange - A target change to apply for computing limbo docs and\n     *        sync state.\n     * @returns A new ViewChange with the given docs, changes, and sync state.\n     */\n    // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n    applyChanges(e, t, n) {\n        const r = this.ra;\n        this.ra = e.ra, this.mutatedKeys = e.mutatedKeys;\n        // Sort changes based on type and query comparator\n        const i = e.oa.M_();\n        i.sort(((e, t) => function __PRIVATE_compareChangeType(e, t) {\n            const order = e => {\n                switch (e) {\n                  case 0 /* ChangeType.Added */ :\n                    return 1;\n\n                  case 2 /* ChangeType.Modified */ :\n                  case 3 /* ChangeType.Metadata */ :\n                    // A metadata change is converted to a modified change at the public\n                    // api layer.  Since we sort by document key and then change type,\n                    // metadata and modified changes must be sorted equivalently.\n                    return 2;\n\n                  case 1 /* ChangeType.Removed */ :\n                    return 0;\n\n                  default:\n                    return fail();\n                }\n            };\n            return order(e) - order(t);\n        }\n        /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (e.type, t.type) || this.na(e.doc, t.doc))), this.aa(n);\n        const s = t ? this.ua() : [], o = 0 === this.ta.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , _ = o !== this.ea;\n        if (this.ea = o, 0 !== i.length || _) {\n            return {\n                snapshot: new ViewSnapshot(this.query, e.ra, r, i, e.mutatedKeys, 0 /* SyncState.Local */ === o, _, \n                /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),\n                ca: s\n            };\n        }\n        // no changes\n        return {\n            ca: s\n        };\n    }\n    /**\n     * Applies an OnlineState change to the view, potentially generating a\n     * ViewChange if the view's syncState changes as a result.\n     */    N_(e) {\n        return this.current && \"Offline\" /* OnlineState.Offline */ === e ? (\n        // If we're offline, set `current` to false and then call applyChanges()\n        // to refresh our syncState and generate a ViewChange as appropriate. We\n        // are guaranteed to get a new TargetChange that sets `current` back to\n        // true once the client is back online.\n        this.current = !1, this.applyChanges({\n            ra: this.ra,\n            oa: new __PRIVATE_DocumentChangeSet,\n            mutatedKeys: this.mutatedKeys,\n            zi: !1\n        }, \n        /* updateLimboDocuments= */ !1)) : {\n            ca: []\n        };\n    }\n    /**\n     * Returns whether the doc for the given key should be in limbo.\n     */    la(e) {\n        // If the remote end says it's part of this query, it's not in limbo.\n        return !this.X_.has(e) && (\n        // The local store doesn't think it's a result, so it shouldn't be in limbo.\n        !!this.ra.has(e) && !this.ra.get(e).hasLocalMutations);\n    }\n    /**\n     * Updates syncedDocuments, current, and limbo docs based on the given change.\n     * Returns the list of changes to which docs are in limbo.\n     */    aa(e) {\n        e && (e.addedDocuments.forEach((e => this.X_ = this.X_.add(e))), e.modifiedDocuments.forEach((e => {})), \n        e.removedDocuments.forEach((e => this.X_ = this.X_.delete(e))), this.current = e.current);\n    }\n    ua() {\n        // We can only determine limbo documents when we're in-sync with the server.\n        if (!this.current) return [];\n        // TODO(klimt): Do this incrementally so that it's not quadratic when\n        // updating many documents.\n                const e = this.ta;\n        this.ta = __PRIVATE_documentKeySet(), this.ra.forEach((e => {\n            this.la(e.key) && (this.ta = this.ta.add(e.key));\n        }));\n        // Diff the new limbo docs with the old limbo docs.\n        const t = [];\n        return e.forEach((e => {\n            this.ta.has(e) || t.push(new __PRIVATE_RemovedLimboDocument(e));\n        })), this.ta.forEach((n => {\n            e.has(n) || t.push(new __PRIVATE_AddedLimboDocument(n));\n        })), t;\n    }\n    /**\n     * Update the in-memory state of the current view with the state read from\n     * persistence.\n     *\n     * We update the query view whenever a client's primary status changes:\n     * - When a client transitions from primary to secondary, it can miss\n     *   LocalStorage updates and its query views may temporarily not be\n     *   synchronized with the state on disk.\n     * - For secondary to primary transitions, the client needs to update the list\n     *   of `syncedDocuments` since secondary clients update their query views\n     *   based purely on synthesized RemoteEvents.\n     *\n     * @param queryResult.documents - The documents that match the query according\n     * to the LocalStore.\n     * @param queryResult.remoteKeys - The keys of the documents that match the\n     * query according to the backend.\n     *\n     * @returns The ViewChange that resulted from this synchronization.\n     */\n    // PORTING NOTE: Multi-tab only.\n    ha(e) {\n        this.X_ = e.ss, this.ta = __PRIVATE_documentKeySet();\n        const t = this.sa(e.documents);\n        return this.applyChanges(t, /*updateLimboDocuments=*/ !0);\n    }\n    /**\n     * Returns a view snapshot as if this query was just listened to. Contains\n     * a document add for every existing document and the `fromCache` and\n     * `hasPendingWrites` status of the already established view.\n     */\n    // PORTING NOTE: Multi-tab only.\n    Pa() {\n        return ViewSnapshot.fromInitialDocuments(this.query, this.ra, this.mutatedKeys, 0 /* SyncState.Local */ === this.ea, this.hasCachedResults);\n    }\n}\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass __PRIVATE_QueryView {\n    constructor(\n    /**\n     * The query itself.\n     */\n    e, \n    /**\n     * The target number created by the client that is used in the watch\n     * stream to identify this query.\n     */\n    t, \n    /**\n     * The view is responsible for computing the final merged truth of what\n     * docs are in the query. It gets notified of local and remote changes,\n     * and applies the query filters and limits to determine the most correct\n     * possible results.\n     */\n    n) {\n        this.query = e, this.targetId = t, this.view = n;\n    }\n}\n\n/** Tracks a limbo resolution. */ class LimboResolution {\n    constructor(e) {\n        this.key = e, \n        /**\n         * Set to true once we've received a document. This is used in\n         * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n         * decide whether it needs to manufacture a delete event for the target once\n         * the target is CURRENT.\n         */\n        this.Ia = !1;\n    }\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */ class __PRIVATE_SyncEngineImpl {\n    constructor(e, t, n, \n    // PORTING NOTE: Manages state synchronization in multi-tab environments.\n    r, i, s) {\n        this.localStore = e, this.remoteStore = t, this.eventManager = n, this.sharedClientState = r, \n        this.currentUser = i, this.maxConcurrentLimboResolutions = s, this.Ta = {}, this.Ea = new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals), \n        this.da = new Map, \n        /**\n         * The keys of documents that are in limbo for which we haven't yet started a\n         * limbo resolution query. The strings in this set are the result of calling\n         * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n         *\n         * The `Set` type was chosen because it provides efficient lookup and removal\n         * of arbitrary elements and it also maintains insertion order, providing the\n         * desired queue-like FIFO semantics.\n         */\n        this.Aa = new Set, \n        /**\n         * Keeps track of the target ID for each document that is in limbo with an\n         * active target.\n         */\n        this.Ra = new SortedMap(DocumentKey.comparator), \n        /**\n         * Keeps track of the information about an active limbo resolution for each\n         * active target ID that was started for the purpose of limbo resolution.\n         */\n        this.Va = new Map, this.ma = new __PRIVATE_ReferenceSet, \n        /** Stores user completion handlers, indexed by User and BatchId. */\n        this.fa = {}, \n        /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n        this.ga = new Map, this.pa = __PRIVATE_TargetIdGenerator.On(), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n        // The primary state is set to `true` or `false` immediately after Firestore\n        // startup. In the interim, a client should only be considered primary if\n        // `isPrimary` is true.\n        this.ya = void 0;\n    }\n    get isPrimaryClient() {\n        return !0 === this.ya;\n    }\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nasync function __PRIVATE_syncEngineListen(e, t) {\n    const n = __PRIVATE_ensureWatchCallbacks(e);\n    let r, i;\n    const s = n.Ea.get(t);\n    if (s) \n    // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n    // already exists when EventManager calls us for the first time. This\n    // happens when the primary tab is already listening to this query on\n    // behalf of another tab and the user of the primary also starts listening\n    // to the query. EventManager will not have an assigned target ID in this\n    // case and calls `listen` to obtain this ID.\n    r = s.targetId, n.sharedClientState.addLocalQueryTarget(r), i = s.view.Pa(); else {\n        const e = await __PRIVATE_localStoreAllocateTarget(n.localStore, __PRIVATE_queryToTarget(t)), s = n.sharedClientState.addLocalQueryTarget(e.targetId);\n        r = e.targetId, i = await __PRIVATE_initializeViewAndComputeSnapshot(n, t, r, \"current\" === s, e.resumeToken), \n        n.isPrimaryClient && __PRIVATE_remoteStoreListen(n.remoteStore, e);\n    }\n    return i;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */ async function __PRIVATE_initializeViewAndComputeSnapshot(e, t, n, r, i) {\n    // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n    // targets based on view changes. This allows us to only depend on Limbo\n    // changes when user code includes queries.\n    e.wa = (t, n, r) => async function __PRIVATE_applyDocChanges(e, t, n, r) {\n        let i = t.view.sa(n);\n        i.zi && (\n        // The query has a limit and some docs were removed, so we need\n        // to re-run the query against the local store to make sure we\n        // didn't lose any good docs that had been past the limit.\n        i = await __PRIVATE_localStoreExecuteQuery(e.localStore, t.query, \n        /* usePreviousResults= */ !1).then((({documents: e}) => t.view.sa(e, i))));\n        const s = r && r.targetChanges.get(t.targetId), o = t.view.applyChanges(i, \n        /* updateLimboDocuments= */ e.isPrimaryClient, s);\n        return __PRIVATE_updateTrackedLimbos(e, t.targetId, o.ca), o.snapshot;\n    }(e, t, n, r);\n    const s = await __PRIVATE_localStoreExecuteQuery(e.localStore, t, \n    /* usePreviousResults= */ !0), o = new __PRIVATE_View(t, s.ss), _ = o.sa(s.documents), a = TargetChange.createSynthesizedTargetChangeForCurrentChange(n, r && \"Offline\" /* OnlineState.Offline */ !== e.onlineState, i), u = o.applyChanges(_, \n    /* updateLimboDocuments= */ e.isPrimaryClient, a);\n    __PRIVATE_updateTrackedLimbos(e, n, u.ca);\n    const c = new __PRIVATE_QueryView(t, n, o);\n    return e.Ea.set(t, c), e.da.has(n) ? e.da.get(n).push(t) : e.da.set(n, [ t ]), u.snapshot;\n}\n\n/** Stops listening to the query. */ async function __PRIVATE_syncEngineUnlisten(e, t) {\n    const n = __PRIVATE_debugCast(e), r = n.Ea.get(t), i = n.da.get(r.targetId);\n    if (i.length > 1) return n.da.set(r.targetId, i.filter((e => !__PRIVATE_queryEquals(e, t)))), \n    void n.Ea.delete(t);\n    // No other queries are mapped to the target, clean up the query and the target.\n        if (n.isPrimaryClient) {\n        // We need to remove the local query target first to allow us to verify\n        // whether any other client is still interested in this target.\n        n.sharedClientState.removeLocalQueryTarget(r.targetId);\n        n.sharedClientState.isActiveQueryTarget(r.targetId) || await __PRIVATE_localStoreReleaseTarget(n.localStore, r.targetId, \n        /*keepPersistedTargetData=*/ !1).then((() => {\n            n.sharedClientState.clearQueryState(r.targetId), __PRIVATE_remoteStoreUnlisten(n.remoteStore, r.targetId), \n            __PRIVATE_removeAndCleanupTarget(n, r.targetId);\n        })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);\n    } else __PRIVATE_removeAndCleanupTarget(n, r.targetId), await __PRIVATE_localStoreReleaseTarget(n.localStore, r.targetId, \n    /*keepPersistedTargetData=*/ !0);\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */ async function __PRIVATE_syncEngineWrite(e, t, n) {\n    const r = __PRIVATE_syncEngineEnsureWriteCallbacks(e);\n    try {\n        const e = await function __PRIVATE_localStoreWriteLocally(e, t) {\n            const n = __PRIVATE_debugCast(e), r = Timestamp.now(), i = t.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet());\n            let s, o;\n            return n.persistence.runTransaction(\"Locally write mutations\", \"readwrite\", (e => {\n                // Figure out which keys do not have a remote version in the cache, this\n                // is needed to create the right overlay mutation: if no remote version\n                // presents, we do not need to create overlays as patch mutations.\n                // TODO(Overlay): Is there a better way to determine this? Using the\n                //  document version does not work because local mutations set them back\n                //  to 0.\n                let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();\n                return n.Xi.getEntries(e, i).next((e => {\n                    _ = e, _.forEach(((e, t) => {\n                        t.isValidDocument() || (a = a.add(e));\n                    }));\n                })).next((() => n.localDocuments.getOverlayedDocuments(e, _))).next((i => {\n                    s = i;\n                    // For non-idempotent mutations (such as `FieldValue.increment()`),\n                    // we record the base state in a separate patch mutation. This is\n                    // later used to guarantee consistent values and prevents flicker\n                    // even if the backend sends us an update that already includes our\n                    // transform.\n                    const o = [];\n                    for (const e of t) {\n                        const t = __PRIVATE_mutationExtractBaseValue(e, s.get(e.key).overlayedDocument);\n                        null != t && \n                        // NOTE: The base state should only be applied if there's some\n                        // existing document to override, so use a Precondition of\n                        // exists=true\n                        o.push(new __PRIVATE_PatchMutation(e.key, t, __PRIVATE_extractFieldMask(t.value.mapValue), Precondition.exists(!0)));\n                    }\n                    return n.mutationQueue.addMutationBatch(e, r, o, t);\n                })).next((t => {\n                    o = t;\n                    const r = t.applyToLocalDocumentSet(s, a);\n                    return n.documentOverlayCache.saveOverlays(e, t.batchId, r);\n                }));\n            })).then((() => ({\n                batchId: o.batchId,\n                changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(s)\n            })));\n        }(r.localStore, t);\n        r.sharedClientState.addPendingMutation(e.batchId), function __PRIVATE_addMutationCallback(e, t, n) {\n            let r = e.fa[e.currentUser.toKey()];\n            r || (r = new SortedMap(__PRIVATE_primitiveComparator));\n            r = r.insert(t, n), e.fa[e.currentUser.toKey()] = r;\n        }\n        /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */ (r, e.batchId, n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e.changes), \n        await __PRIVATE_fillWritePipeline(r.remoteStore);\n    } catch (e) {\n        // If we can't persist the mutation, we reject the user callback and\n        // don't send the mutation. The user can then retry the write.\n        const t = __PRIVATE_wrapInUserErrorIfRecoverable(e, \"Failed to persist write\");\n        n.reject(t);\n    }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */ async function __PRIVATE_syncEngineApplyRemoteEvent(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    try {\n        const e = await __PRIVATE_localStoreApplyRemoteEventToLocalCache(n.localStore, t);\n        // Update `receivedDocument` as appropriate for any limbo targets.\n                t.targetChanges.forEach(((e, t) => {\n            const r = n.Va.get(t);\n            r && (\n            // Since this is a limbo resolution lookup, it's for a single document\n            // and it could be added, modified, or removed, but not a combination.\n            __PRIVATE_hardAssert(e.addedDocuments.size + e.modifiedDocuments.size + e.removedDocuments.size <= 1), \n            e.addedDocuments.size > 0 ? r.Ia = !0 : e.modifiedDocuments.size > 0 ? __PRIVATE_hardAssert(r.Ia) : e.removedDocuments.size > 0 && (__PRIVATE_hardAssert(r.Ia), \n            r.Ia = !1));\n        })), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e, t);\n    } catch (e) {\n        await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n    }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */ function __PRIVATE_syncEngineApplyOnlineStateChange(e, t, n) {\n    const r = __PRIVATE_debugCast(e);\n    // If we are the secondary client, we explicitly ignore the remote store's\n    // online state (the local client may go offline, even though the primary\n    // tab remains online) and only apply the primary tab's online state from\n    // SharedClientState.\n        if (r.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !r.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {\n        const e = [];\n        r.Ea.forEach(((n, r) => {\n            const i = r.view.N_(t);\n            i.snapshot && e.push(i.snapshot);\n        })), function __PRIVATE_eventManagerOnOnlineStateChange(e, t) {\n            const n = __PRIVATE_debugCast(e);\n            n.onlineState = t;\n            let r = !1;\n            n.queries.forEach(((e, n) => {\n                for (const e of n.listeners) \n                // Run global snapshot listeners if a consistent snapshot has been emitted.\n                e.N_(t) && (r = !0);\n            })), r && __PRIVATE_raiseSnapshotsInSyncEvent(n);\n        }(r.eventManager, t), e.length && r.Ta.r_(e), r.onlineState = t, r.isPrimaryClient && r.sharedClientState.setOnlineState(t);\n    }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */ async function __PRIVATE_syncEngineRejectListen(e, t, n) {\n    const r = __PRIVATE_debugCast(e);\n    // PORTING NOTE: Multi-tab only.\n        r.sharedClientState.updateQueryState(t, \"rejected\", n);\n    const i = r.Va.get(t), s = i && i.key;\n    if (s) {\n        // TODO(klimt): We really only should do the following on permission\n        // denied errors, but we don't have the cause code here.\n        // It's a limbo doc. Create a synthetic event saying it was deleted.\n        // This is kind of a hack. Ideally, we would have a method in the local\n        // store to purge a document. However, it would be tricky to keep all of\n        // the local store's invariants with another method.\n        let e = new SortedMap(DocumentKey.comparator);\n        // TODO(b/217189216): This limbo document should ideally have a read time,\n        // so that it is picked up by any read-time based scans. The backend,\n        // however, does not send a read time for target removals.\n                e = e.insert(s, MutableDocument.newNoDocument(s, SnapshotVersion.min()));\n        const n = __PRIVATE_documentKeySet().add(s), i = new RemoteEvent(SnapshotVersion.min(), \n        /* targetChanges= */ new Map, \n        /* targetMismatches= */ new SortedMap(__PRIVATE_primitiveComparator), e, n);\n        await __PRIVATE_syncEngineApplyRemoteEvent(r, i), \n        // Since this query failed, we won't want to manually unlisten to it.\n        // We only remove it from bookkeeping after we successfully applied the\n        // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n        // this query when the RemoteStore restarts the Watch stream, which should\n        // re-trigger the target failure.\n        r.Ra = r.Ra.remove(s), r.Va.delete(t), __PRIVATE_pumpEnqueuedLimboResolutions(r);\n    } else await __PRIVATE_localStoreReleaseTarget(r.localStore, t, \n    /* keepPersistedTargetData */ !1).then((() => __PRIVATE_removeAndCleanupTarget(r, t, n))).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);\n}\n\nasync function __PRIVATE_syncEngineApplySuccessfulWrite(e, t) {\n    const n = __PRIVATE_debugCast(e), r = t.batch.batchId;\n    try {\n        const e = await __PRIVATE_localStoreAcknowledgeBatch(n.localStore, t);\n        // The local store may or may not be able to apply the write result and\n        // raise events immediately (depending on whether the watcher is caught\n        // up), so we raise user callbacks first so that they consistently happen\n        // before listen events.\n                __PRIVATE_processUserCallback(n, r, /*error=*/ null), __PRIVATE_triggerPendingWritesCallbacks(n, r), \n        n.sharedClientState.updateMutationState(r, \"acknowledged\"), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e);\n    } catch (e) {\n        await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);\n    }\n}\n\nasync function __PRIVATE_syncEngineRejectFailedWrite(e, t, n) {\n    const r = __PRIVATE_debugCast(e);\n    try {\n        const e = await function __PRIVATE_localStoreRejectBatch(e, t) {\n            const n = __PRIVATE_debugCast(e);\n            return n.persistence.runTransaction(\"Reject batch\", \"readwrite-primary\", (e => {\n                let r;\n                return n.mutationQueue.lookupMutationBatch(e, t).next((t => (__PRIVATE_hardAssert(null !== t), \n                r = t.keys(), n.mutationQueue.removeMutationBatch(e, t)))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, r))).next((() => n.localDocuments.getDocuments(e, r)));\n            }));\n        }\n        /**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */ (r.localStore, t);\n        // The local store may or may not be able to apply the write result and\n        // raise events immediately (depending on whether the watcher is caught up),\n        // so we raise user callbacks first so that they consistently happen before\n        // listen events.\n                __PRIVATE_processUserCallback(r, t, n), __PRIVATE_triggerPendingWritesCallbacks(r, t), \n        r.sharedClientState.updateMutationState(t, \"rejected\", n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e);\n    } catch (n) {\n        await __PRIVATE_ignoreIfPrimaryLeaseLoss(n);\n    }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */ async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    __PRIVATE_canUseNetwork(n.remoteStore) || __PRIVATE_logDebug(\"SyncEngine\", \"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.\");\n    try {\n        const e = await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e) {\n            const t = __PRIVATE_debugCast(e);\n            return t.persistence.runTransaction(\"Get highest unacknowledged batch id\", \"readonly\", (e => t.mutationQueue.getHighestUnacknowledgedBatchId(e)));\n        }(n.localStore);\n        if (-1 === e) \n        // Trigger the callback right away if there is no pending writes at the moment.\n        return void t.resolve();\n        const r = n.ga.get(e) || [];\n        r.push(t), n.ga.set(e, r);\n    } catch (e) {\n        const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, \"Initialization of waitForPendingWrites() operation failed\");\n        t.reject(n);\n    }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */ function __PRIVATE_triggerPendingWritesCallbacks(e, t) {\n    (e.ga.get(t) || []).forEach((e => {\n        e.resolve();\n    })), e.ga.delete(t);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */ function __PRIVATE_processUserCallback(e, t, n) {\n    const r = __PRIVATE_debugCast(e);\n    let i = r.fa[r.currentUser.toKey()];\n    // NOTE: Mutations restored from persistence won't have callbacks, so it's\n    // okay for there to be no callback for this ID.\n        if (i) {\n        const e = i.get(t);\n        e && (n ? e.reject(n) : e.resolve(), i = i.remove(t)), r.fa[r.currentUser.toKey()] = i;\n    }\n}\n\nfunction __PRIVATE_removeAndCleanupTarget(e, t, n = null) {\n    e.sharedClientState.removeLocalQueryTarget(t);\n    for (const r of e.da.get(t)) e.Ea.delete(r), n && e.Ta.Sa(r, n);\n    if (e.da.delete(t), e.isPrimaryClient) {\n        e.ma.Ar(t).forEach((t => {\n            e.ma.containsKey(t) || \n            // We removed the last reference for this key\n            __PRIVATE_removeLimboTarget(e, t);\n        }));\n    }\n}\n\nfunction __PRIVATE_removeLimboTarget(e, t) {\n    e.Aa.delete(t.path.canonicalString());\n    // It's possible that the target already got removed because the query failed. In that case,\n    // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n    const n = e.Ra.get(t);\n    null !== n && (__PRIVATE_remoteStoreUnlisten(e.remoteStore, n), e.Ra = e.Ra.remove(t), \n    e.Va.delete(n), __PRIVATE_pumpEnqueuedLimboResolutions(e));\n}\n\nfunction __PRIVATE_updateTrackedLimbos(e, t, n) {\n    for (const r of n) if (r instanceof __PRIVATE_AddedLimboDocument) e.ma.addReference(r.key, t), \n    __PRIVATE_trackLimboChange(e, r); else if (r instanceof __PRIVATE_RemovedLimboDocument) {\n        __PRIVATE_logDebug(\"SyncEngine\", \"Document no longer in limbo: \" + r.key), e.ma.removeReference(r.key, t);\n        e.ma.containsKey(r.key) || \n        // We removed the last reference for this key\n        __PRIVATE_removeLimboTarget(e, r.key);\n    } else fail();\n}\n\nfunction __PRIVATE_trackLimboChange(e, t) {\n    const n = t.key, r = n.path.canonicalString();\n    e.Ra.get(n) || e.Aa.has(r) || (__PRIVATE_logDebug(\"SyncEngine\", \"New document in limbo: \" + n), \n    e.Aa.add(r), __PRIVATE_pumpEnqueuedLimboResolutions(e));\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */ function __PRIVATE_pumpEnqueuedLimboResolutions(e) {\n    for (;e.Aa.size > 0 && e.Ra.size < e.maxConcurrentLimboResolutions; ) {\n        const t = e.Aa.values().next().value;\n        e.Aa.delete(t);\n        const n = new DocumentKey(ResourcePath.fromString(t)), r = e.pa.next();\n        e.Va.set(r, new LimboResolution(n)), e.Ra = e.Ra.insert(n, r), __PRIVATE_remoteStoreListen(e.remoteStore, new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(n.path)), r, \"TargetPurposeLimboResolution\" /* TargetPurpose.LimboResolution */ , __PRIVATE_ListenSequence.ae));\n    }\n}\n\nasync function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, t, n) {\n    const r = __PRIVATE_debugCast(e), i = [], s = [], o = [];\n    r.Ea.isEmpty() || (r.Ea.forEach(((e, _) => {\n        o.push(r.wa(_, t, n).then((e => {\n            // Update views if there are actual changes.\n            if (\n            // If there are changes, or we are handling a global snapshot, notify\n            // secondary clients to update query state.\n            (e || n) && r.isPrimaryClient && r.sharedClientState.updateQueryState(_.targetId, (null == e ? void 0 : e.fromCache) ? \"not-current\" : \"current\"), \n            e) {\n                i.push(e);\n                const t = __PRIVATE_LocalViewChanges.qi(_.targetId, e);\n                s.push(t);\n            }\n        })));\n    })), await Promise.all(o), r.Ta.r_(i), await async function __PRIVATE_localStoreNotifyLocalViewChanges(e, t) {\n        const n = __PRIVATE_debugCast(e);\n        try {\n            await n.persistence.runTransaction(\"notifyLocalViewChanges\", \"readwrite\", (e => PersistencePromise.forEach(t, (t => PersistencePromise.forEach(t.Li, (r => n.persistence.referenceDelegate.addReference(e, t.targetId, r))).next((() => PersistencePromise.forEach(t.ki, (r => n.persistence.referenceDelegate.removeReference(e, t.targetId, r)))))))));\n        } catch (e) {\n            if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;\n            // If `notifyLocalViewChanges` fails, we did not advance the sequence\n            // number for the documents that were included in this transaction.\n            // This might trigger them to be deleted earlier than they otherwise\n            // would have, but it should not invalidate the integrity of the data.\n            __PRIVATE_logDebug(\"LocalStore\", \"Failed to update sequence numbers: \" + e);\n        }\n        for (const e of t) {\n            const t = e.targetId;\n            if (!e.fromCache) {\n                const e = n.Ji.get(t), r = e.snapshotVersion, i = e.withLastLimboFreeSnapshotVersion(r);\n                // Advance the last limbo free snapshot version\n                                n.Ji = n.Ji.insert(t, i);\n            }\n        }\n    }(r.localStore, s));\n}\n\nasync function __PRIVATE_syncEngineHandleCredentialChange(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    if (!n.currentUser.isEqual(t)) {\n        __PRIVATE_logDebug(\"SyncEngine\", \"User change. New user:\", t.toKey());\n        const e = await __PRIVATE_localStoreHandleUserChange(n.localStore, t);\n        n.currentUser = t, \n        // Fails tasks waiting for pending writes requested by previous user.\n        function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e, t) {\n            e.ga.forEach((e => {\n                e.forEach((e => {\n                    e.reject(new FirestoreError(v.CANCELLED, t));\n                }));\n            })), e.ga.clear();\n        }(n, \"'waitForPendingWrites' promise is rejected due to a user change.\"), \n        // TODO(b/114226417): Consider calling this only in the primary tab.\n        n.sharedClientState.handleUserChange(t, e.removedBatchIds, e.addedBatchIds), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e.ts);\n    }\n}\n\nfunction __PRIVATE_syncEngineGetRemoteKeysForTarget(e, t) {\n    const n = __PRIVATE_debugCast(e), r = n.Va.get(t);\n    if (r && r.Ia) return __PRIVATE_documentKeySet().add(r.key);\n    {\n        let e = __PRIVATE_documentKeySet();\n        const r = n.da.get(t);\n        if (!r) return e;\n        for (const t of r) {\n            const r = n.Ea.get(t);\n            e = e.unionWith(r.view.ia);\n        }\n        return e;\n    }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */ async function __PRIVATE_synchronizeViewAndComputeSnapshot(e, t) {\n    const n = __PRIVATE_debugCast(e), r = await __PRIVATE_localStoreExecuteQuery(n.localStore, t.query, \n    /* usePreviousResults= */ !0), i = t.view.ha(r);\n    return n.isPrimaryClient && __PRIVATE_updateTrackedLimbos(n, t.targetId, i.ca), \n    i;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    return __PRIVATE_localStoreGetNewDocumentChanges(n.localStore, t).then((e => __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e)));\n}\n\n/** Applies a mutation state to an existing batch.  */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineApplyBatchState(e, t, n, r) {\n    const i = __PRIVATE_debugCast(e), s = await function __PRIVATE_localStoreLookupMutationDocuments(e, t) {\n        const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.mutationQueue);\n        return n.persistence.runTransaction(\"Lookup mutation documents\", \"readonly\", (e => r.Dn(e, t).next((t => t ? n.localDocuments.getDocuments(e, t) : PersistencePromise.resolve(null)))));\n    }\n    // PORTING NOTE: Multi-Tab only.\n    (i.localStore, t);\n    null !== s ? (\"pending\" === n ? \n    // If we are the primary client, we need to send this write to the\n    // backend. Secondary clients will ignore these writes since their remote\n    // connection is disabled.\n    await __PRIVATE_fillWritePipeline(i.remoteStore) : \"acknowledged\" === n || \"rejected\" === n ? (\n    // NOTE: Both these methods are no-ops for batches that originated from\n    // other clients.\n    __PRIVATE_processUserCallback(i, t, r || null), __PRIVATE_triggerPendingWritesCallbacks(i, t), \n    function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e, t) {\n        __PRIVATE_debugCast(__PRIVATE_debugCast(e).mutationQueue).Cn(t);\n    }\n    // PORTING NOTE: Multi-Tab only.\n    (i.localStore, t)) : fail(), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, s)) : \n    // A throttled tab may not have seen the mutation before it was completed\n    // and removed from the mutation queue, in which case we won't have cached\n    // the affected documents. In this case we can safely ignore the update\n    // since that means we didn't apply the mutation locally at all (if we\n    // had, we would have cached the affected documents), and so we will just\n    // see any resulting document changes via normal remote document updates\n    // as applicable.\n    __PRIVATE_logDebug(\"SyncEngine\", \"Cannot apply mutation batch with id: \" + t);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineApplyPrimaryState(e, t) {\n    const n = __PRIVATE_debugCast(e);\n    if (__PRIVATE_ensureWatchCallbacks(n), __PRIVATE_syncEngineEnsureWriteCallbacks(n), \n    !0 === t && !0 !== n.ya) {\n        // Secondary tabs only maintain Views for their local listeners and the\n        // Views internal state may not be 100% populated (in particular\n        // secondary tabs don't track syncedDocuments, the set of documents the\n        // server considers to be in the target). So when a secondary becomes\n        // primary, we need to need to make sure that all views for all targets\n        // match the state on disk.\n        const e = n.sharedClientState.getAllActiveQueryTargets(), t = await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e.toArray());\n        n.ya = !0, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !0);\n        for (const e of t) __PRIVATE_remoteStoreListen(n.remoteStore, e);\n    } else if (!1 === t && !1 !== n.ya) {\n        const e = [];\n        let t = Promise.resolve();\n        n.da.forEach(((r, i) => {\n            n.sharedClientState.isLocalQueryTarget(i) ? e.push(i) : t = t.then((() => (__PRIVATE_removeAndCleanupTarget(n, i), \n            __PRIVATE_localStoreReleaseTarget(n.localStore, i, \n            /*keepPersistedTargetData=*/ !0)))), __PRIVATE_remoteStoreUnlisten(n.remoteStore, i);\n        })), await t, await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e), \n        // PORTING NOTE: Multi-Tab only.\n        function __PRIVATE_resetLimboDocuments(e) {\n            const t = __PRIVATE_debugCast(e);\n            t.Va.forEach(((e, n) => {\n                __PRIVATE_remoteStoreUnlisten(t.remoteStore, n);\n            })), t.ma.Rr(), t.Va = new Map, t.Ra = new SortedMap(DocumentKey.comparator);\n        }\n        /**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n        // PORTING NOTE: Multi-Tab only.\n        (n), n.ya = !1, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !1);\n    }\n}\n\nasync function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e, t, n) {\n    const r = __PRIVATE_debugCast(e), i = [], s = [];\n    for (const e of t) {\n        let t;\n        const n = r.da.get(e);\n        if (n && 0 !== n.length) {\n            // For queries that have a local View, we fetch their current state\n            // from LocalStore (as the resume token and the snapshot version\n            // might have changed) and reconcile their views with the persisted\n            // state (the list of syncedDocuments may have gotten out of sync).\n            t = await __PRIVATE_localStoreAllocateTarget(r.localStore, __PRIVATE_queryToTarget(n[0]));\n            for (const e of n) {\n                const t = r.Ea.get(e), n = await __PRIVATE_synchronizeViewAndComputeSnapshot(r, t);\n                n.snapshot && s.push(n.snapshot);\n            }\n        } else {\n            // For queries that never executed on this client, we need to\n            // allocate the target in LocalStore and initialize a new View.\n            const n = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e);\n            t = await __PRIVATE_localStoreAllocateTarget(r.localStore, n), await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(n), e, \n            /*current=*/ !1, t.resumeToken);\n        }\n        i.push(t);\n    }\n    return r.Ta.r_(s), i;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_synthesizeTargetToQuery(e) {\n    return __PRIVATE_newQuery(e.path, e.collectionGroup, e.orderBy, e.filters, e.limit, \"F\" /* LimitType.First */ , e.startAt, e.endAt);\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nfunction __PRIVATE_syncEngineGetActiveClients(e) {\n    return function __PRIVATE_localStoreGetActiveClients(e) {\n        return __PRIVATE_debugCast(__PRIVATE_debugCast(e).persistence).Ni();\n    }(__PRIVATE_debugCast(e).localStore);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function __PRIVATE_syncEngineApplyTargetState(e, t, n, r) {\n    const i = __PRIVATE_debugCast(e);\n    if (i.ya) \n    // If we receive a target state notification via WebStorage, we are\n    // either already secondary or another tab has taken the primary lease.\n    return void __PRIVATE_logDebug(\"SyncEngine\", \"Ignoring unexpected query state notification.\");\n    const s = i.da.get(t);\n    if (s && s.length > 0) switch (n) {\n      case \"current\":\n      case \"not-current\":\n        {\n            const e = await __PRIVATE_localStoreGetNewDocumentChanges(i.localStore, __PRIVATE_queryCollectionGroup(s[0])), r = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(t, \"current\" === n, ByteString.EMPTY_BYTE_STRING);\n            await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, e, r);\n            break;\n        }\n\n      case \"rejected\":\n        await __PRIVATE_localStoreReleaseTarget(i.localStore, t, \n        /* keepPersistedTargetData */ !0), __PRIVATE_removeAndCleanupTarget(i, t, r);\n        break;\n\n      default:\n        fail();\n    }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */ async function __PRIVATE_syncEngineApplyActiveTargetsChange(e, t, n) {\n    const r = __PRIVATE_ensureWatchCallbacks(e);\n    if (r.ya) {\n        for (const e of t) {\n            if (r.da.has(e)) {\n                // A target might have been added in a previous attempt\n                __PRIVATE_logDebug(\"SyncEngine\", \"Adding an already active target \" + e);\n                continue;\n            }\n            const t = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e), n = await __PRIVATE_localStoreAllocateTarget(r.localStore, t);\n            await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(t), n.targetId, \n            /*current=*/ !1, n.resumeToken), __PRIVATE_remoteStoreListen(r.remoteStore, n);\n        }\n        for (const e of n) \n        // Check that the target is still active since the target might have been\n        // removed if it has been rejected by the backend.\n        r.da.has(e) && \n        // Release queries that are still active.\n        await __PRIVATE_localStoreReleaseTarget(r.localStore, e, \n        /* keepPersistedTargetData */ !1).then((() => {\n            __PRIVATE_remoteStoreUnlisten(r.remoteStore, e), __PRIVATE_removeAndCleanupTarget(r, e);\n        })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);\n    }\n}\n\nfunction __PRIVATE_ensureWatchCallbacks(e) {\n    const t = __PRIVATE_debugCast(e);\n    return t.remoteStore.remoteSyncer.applyRemoteEvent = __PRIVATE_syncEngineApplyRemoteEvent.bind(null, t), \n    t.remoteStore.remoteSyncer.getRemoteKeysForTarget = __PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null, t), \n    t.remoteStore.remoteSyncer.rejectListen = __PRIVATE_syncEngineRejectListen.bind(null, t), \n    t.Ta.r_ = __PRIVATE_eventManagerOnWatchChange.bind(null, t.eventManager), t.Ta.Sa = __PRIVATE_eventManagerOnWatchError.bind(null, t.eventManager), \n    t;\n}\n\nfunction __PRIVATE_syncEngineEnsureWriteCallbacks(e) {\n    const t = __PRIVATE_debugCast(e);\n    return t.remoteStore.remoteSyncer.applySuccessfulWrite = __PRIVATE_syncEngineApplySuccessfulWrite.bind(null, t), \n    t.remoteStore.remoteSyncer.rejectFailedWrite = __PRIVATE_syncEngineRejectFailedWrite.bind(null, t), \n    t;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */ function __PRIVATE_syncEngineLoadBundle(e, t, n) {\n    const r = __PRIVATE_debugCast(e);\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        (\n    /** Loads a bundle and returns the list of affected collection groups. */\n    async function __PRIVATE_loadBundleImpl(e, t, n) {\n        try {\n            const r = await t.getMetadata();\n            if (await function __PRIVATE_localStoreHasNewerBundle(e, t) {\n                const n = __PRIVATE_debugCast(e), r = __PRIVATE_fromVersion(t.createTime);\n                return n.persistence.runTransaction(\"hasNewerBundle\", \"readonly\", (e => n.Qr.getBundleMetadata(e, t.id))).then((e => !!e && e.createTime.compareTo(r) >= 0));\n            }\n            /**\n * Saves the given `BundleMetadata` to local persistence.\n */ (e.localStore, r)) return await t.close(), n._completeWith(function __PRIVATE_bundleSuccessProgress(e) {\n                return {\n                    taskState: \"Success\",\n                    documentsLoaded: e.totalDocuments,\n                    bytesLoaded: e.totalBytes,\n                    totalDocuments: e.totalDocuments,\n                    totalBytes: e.totalBytes\n                };\n            }(r)), Promise.resolve(new Set);\n            n._updateProgress(__PRIVATE_bundleInitialProgress(r));\n            const i = new __PRIVATE_BundleLoader(r, e.localStore, t.serializer);\n            let s = await t.ba();\n            for (;s; ) {\n                const e = await i.H_(s);\n                e && n._updateProgress(e), s = await t.ba();\n            }\n            const o = await i.complete();\n            return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, o.Z_, \n            /* remoteEvent */ void 0), \n            // Save metadata, so loading the same bundle will skip.\n            await function __PRIVATE_localStoreSaveBundle(e, t) {\n                const n = __PRIVATE_debugCast(e);\n                return n.persistence.runTransaction(\"Save bundle\", \"readwrite\", (e => n.Qr.saveBundleMetadata(e, t)));\n            }\n            /**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */ (e.localStore, r), n._completeWith(o.progress), Promise.resolve(o.Y_);\n        } catch (e) {\n            return __PRIVATE_logWarn(\"SyncEngine\", `Loading bundle failed with ${e}`), n._failWith(e), \n            Promise.resolve(new Set);\n        }\n    }\n    /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n    /**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */)(r, t, n).then((e => {\n        r.sharedClientState.notifyBundleLoaded(e);\n    }));\n}\n\nclass MemoryOfflineComponentProvider {\n    constructor() {\n        this.synchronizeTabs = !1;\n    }\n    async initialize(e) {\n        this.serializer = __PRIVATE_newSerializer(e.databaseInfo.databaseId), this.sharedClientState = this.createSharedClientState(e), \n        this.persistence = this.createPersistence(e), await this.persistence.start(), this.localStore = this.createLocalStore(e), \n        this.gcScheduler = this.createGarbageCollectionScheduler(e, this.localStore), this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(e, this.localStore);\n    }\n    createGarbageCollectionScheduler(e, t) {\n        return null;\n    }\n    createIndexBackfillerScheduler(e, t) {\n        return null;\n    }\n    createLocalStore(e) {\n        return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer);\n    }\n    createPersistence(e) {\n        return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.zr, this.serializer);\n    }\n    createSharedClientState(e) {\n        return new __PRIVATE_MemorySharedClientState;\n    }\n    async terminate() {\n        this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(), \n        await this.persistence.shutdown();\n    }\n}\n\nclass __PRIVATE_LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider {\n    constructor(e) {\n        super(), this.cacheSizeBytes = e;\n    }\n    createGarbageCollectionScheduler(e, t) {\n        __PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate);\n        const n = this.persistence.referenceDelegate.garbageCollector;\n        return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);\n    }\n    createPersistence(e) {\n        const t = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;\n        return new __PRIVATE_MemoryPersistence((e => __PRIVATE_MemoryLruDelegate.zr(e, t)), this.serializer);\n    }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */ class __PRIVATE_IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider {\n    constructor(e, t, n) {\n        super(), this.Da = e, this.cacheSizeBytes = t, this.forceOwnership = n, this.synchronizeTabs = !1;\n    }\n    async initialize(e) {\n        await super.initialize(e), await this.Da.initialize(this, e), \n        // Enqueue writes from a previous session\n        await __PRIVATE_syncEngineEnsureWriteCallbacks(this.Da.syncEngine), await __PRIVATE_fillWritePipeline(this.Da.remoteStore), \n        // NOTE: This will immediately call the listener, so we make sure to\n        // set it after localStore / remoteStore are started.\n        await this.persistence.Vi((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), \n        this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), \n        Promise.resolve())));\n    }\n    createLocalStore(e) {\n        return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer);\n    }\n    createGarbageCollectionScheduler(e, t) {\n        const n = this.persistence.referenceDelegate.garbageCollector;\n        return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);\n    }\n    createIndexBackfillerScheduler(e, t) {\n        const n = new __PRIVATE_IndexBackfiller(t, this.persistence);\n        return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue, n);\n    }\n    createPersistence(e) {\n        const t = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;\n        return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs, t, e.clientId, n, e.asyncQueue, __PRIVATE_getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership);\n    }\n    createSharedClientState(e) {\n        return new __PRIVATE_MemorySharedClientState;\n    }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */ class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider {\n    constructor(e, t) {\n        super(e, t, /* forceOwnership= */ !1), this.Da = e, this.cacheSizeBytes = t, this.synchronizeTabs = !0;\n    }\n    async initialize(e) {\n        await super.initialize(e);\n        const t = this.Da.syncEngine;\n        this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState && (this.sharedClientState.syncEngine = {\n            Gs: __PRIVATE_syncEngineApplyBatchState.bind(null, t),\n            zs: __PRIVATE_syncEngineApplyTargetState.bind(null, t),\n            js: __PRIVATE_syncEngineApplyActiveTargetsChange.bind(null, t),\n            Ni: __PRIVATE_syncEngineGetActiveClients.bind(null, t),\n            Ws: __PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null, t)\n        }, await this.sharedClientState.start()), \n        // NOTE: This will immediately call the listener, so we make sure to\n        // set it after localStore / remoteStore are started.\n        await this.persistence.Vi((async e => {\n            await __PRIVATE_syncEngineApplyPrimaryState(this.Da.syncEngine, e), this.gcScheduler && (e && !this.gcScheduler.started ? this.gcScheduler.start() : e || this.gcScheduler.stop()), \n            this.indexBackfillerScheduler && (e && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : e || this.indexBackfillerScheduler.stop());\n        }));\n    }\n    createSharedClientState(e) {\n        const t = __PRIVATE_getWindow();\n        if (!__PRIVATE_WebStorageSharedClientState.v(t)) throw new FirestoreError(v.UNIMPLEMENTED, \"IndexedDB persistence is only available on platforms that support LocalStorage.\");\n        const n = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey);\n        return new __PRIVATE_WebStorageSharedClientState(t, e.asyncQueue, n, e.clientId, e.initialUser);\n    }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */ class OnlineComponentProvider {\n    async initialize(e, t) {\n        this.localStore || (this.localStore = e.localStore, this.sharedClientState = e.sharedClientState, \n        this.datastore = this.createDatastore(t), this.remoteStore = this.createRemoteStore(t), \n        this.eventManager = this.createEventManager(t), this.syncEngine = this.createSyncEngine(t, \n        /* startAsPrimary=*/ !e.synchronizeTabs), this.sharedClientState.onlineStateHandler = e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 1 /* OnlineStateSource.SharedClientState */), \n        this.remoteStore.remoteSyncer.handleCredentialChange = __PRIVATE_syncEngineHandleCredentialChange.bind(null, this.syncEngine), \n        await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient));\n    }\n    createEventManager(e) {\n        return function __PRIVATE_newEventManager() {\n            return new __PRIVATE_EventManagerImpl;\n        }();\n    }\n    createDatastore(e) {\n        const t = __PRIVATE_newSerializer(e.databaseInfo.databaseId), n = function __PRIVATE_newConnection(e) {\n            return new __PRIVATE_WebChannelConnection(e);\n        }\n        /** Return the Platform-specific connectivity monitor. */ (e.databaseInfo);\n        return function __PRIVATE_newDatastore(e, t, n, r) {\n            return new __PRIVATE_DatastoreImpl(e, t, n, r);\n        }(e.authCredentials, e.appCheckCredentials, n, t);\n    }\n    createRemoteStore(e) {\n        return function __PRIVATE_newRemoteStore(e, t, n, r, i) {\n            return new __PRIVATE_RemoteStoreImpl(e, t, n, r, i);\n        }\n        /** Re-enables the network. Idempotent. */ (this.localStore, this.datastore, e.asyncQueue, (e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 0 /* OnlineStateSource.RemoteStore */)), function __PRIVATE_newConnectivityMonitor() {\n            return __PRIVATE_BrowserConnectivityMonitor.v() ? new __PRIVATE_BrowserConnectivityMonitor : new __PRIVATE_NoopConnectivityMonitor;\n        }());\n    }\n    createSyncEngine(e, t) {\n        return function __PRIVATE_newSyncEngine(e, t, n, \n        // PORTING NOTE: Manages state synchronization in multi-tab environments.\n        r, i, s, o) {\n            const _ = new __PRIVATE_SyncEngineImpl(e, t, n, r, i, s);\n            return o && (_.ya = !0), _;\n        }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, e.initialUser, e.maxConcurrentLimboResolutions, t);\n    }\n    terminate() {\n        return async function __PRIVATE_remoteStoreShutdown(e) {\n            const t = __PRIVATE_debugCast(e);\n            __PRIVATE_logDebug(\"RemoteStore\", \"RemoteStore shutting down.\"), t.y_.add(5 /* OfflineCause.Shutdown */), \n            await __PRIVATE_disableNetworkInternal(t), t.S_.shutdown(), \n            // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n            // triggering spurious listener events with cached data, etc.\n            t.b_.set(\"Unknown\" /* OnlineState.Unknown */);\n        }(this.remoteStore);\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n *        will read.\n */\nfunction __PRIVATE_toByteStreamReaderHelper(e, t = 10240) {\n    let n = 0;\n    // The TypeScript definition for ReadableStreamReader changed. We use\n    // `any` here to allow this code to compile with different versions.\n    // See https://github.com/microsoft/TypeScript/issues/42970\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        return {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        async read() {\n            if (n < e.byteLength) {\n                const r = {\n                    value: e.slice(n, n + t),\n                    done: !1\n                };\n                return n += t, r;\n            }\n            return {\n                done: !0\n            };\n        },\n        async cancel() {},\n        releaseLock() {},\n        closed: Promise.resolve()\n    };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * A wrapper implementation of Observer<T> that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nclass __PRIVATE_AsyncObserver {\n    constructor(e) {\n        this.observer = e, \n        /**\n         * When set to true, will not raise future events. Necessary to deal with\n         * async detachment of listener.\n         */\n        this.muted = !1;\n    }\n    next(e) {\n        this.observer.next && this.va(this.observer.next, e);\n    }\n    error(e) {\n        this.observer.error ? this.va(this.observer.error, e) : __PRIVATE_logError(\"Uncaught Error in snapshot listener:\", e.toString());\n    }\n    Ca() {\n        this.muted = !0;\n    }\n    va(e, t) {\n        this.muted || setTimeout((() => {\n            this.muted || e(t);\n        }), 0);\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */ class __PRIVATE_BundleReaderImpl {\n    constructor(\n    /** The reader to read from underlying binary bundle data source. */\n    e, t) {\n        this.Fa = e, this.serializer = t, \n        /** Cached bundle metadata. */\n        this.metadata = new __PRIVATE_Deferred, \n        /**\n         * Internal buffer to hold bundle content, accumulating incomplete element\n         * content.\n         */\n        this.buffer = new Uint8Array, this.Ma = function __PRIVATE_newTextDecoder() {\n            return new TextDecoder(\"utf-8\");\n        }(), \n        // Read the metadata (which is the first element).\n        this.xa().then((e => {\n            e && e.z_() ? this.metadata.resolve(e.G_.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\\n             ${JSON.stringify(null == e ? void 0 : e.G_)}`));\n        }), (e => this.metadata.reject(e)));\n    }\n    close() {\n        return this.Fa.cancel();\n    }\n    async getMetadata() {\n        return this.metadata.promise;\n    }\n    async ba() {\n        // Makes sure metadata is read before proceeding.\n        return await this.getMetadata(), this.xa();\n    }\n    /**\n     * Reads from the head of internal buffer, and pulling more data from\n     * underlying stream if a complete element cannot be found, until an\n     * element(including the prefixed length and the JSON string) is found.\n     *\n     * Once a complete element is read, it is dropped from internal buffer.\n     *\n     * Returns either the bundled element, or null if we have reached the end of\n     * the stream.\n     */    async xa() {\n        const e = await this.Oa();\n        if (null === e) return null;\n        const t = this.Ma.decode(e), n = Number(t);\n        isNaN(n) && this.Na(`length string (${t}) is not valid number`);\n        const r = await this.Ba(n);\n        return new __PRIVATE_SizedBundleElement(JSON.parse(r), e.length + n);\n    }\n    /** First index of '{' from the underlying buffer. */    La() {\n        return this.buffer.findIndex((e => e === \"{\".charCodeAt(0)));\n    }\n    /**\n     * Reads from the beginning of the internal buffer, until the first '{', and\n     * return the content.\n     *\n     * If reached end of the stream, returns a null.\n     */    async Oa() {\n        for (;this.La() < 0; ) {\n            if (await this.ka()) break;\n        }\n        // Broke out of the loop because underlying stream is closed, and there\n        // happens to be no more data to process.\n                if (0 === this.buffer.length) return null;\n        const e = this.La();\n        // Broke out of the loop because underlying stream is closed, but still\n        // cannot find an open bracket.\n                e < 0 && this.Na(\"Reached the end of bundle when a length string is expected.\");\n        const t = this.buffer.slice(0, e);\n        // Update the internal buffer to drop the read length.\n                return this.buffer = this.buffer.slice(e), t;\n    }\n    /**\n     * Reads from a specified position from the internal buffer, for a specified\n     * number of bytes, pulling more data from the underlying stream if needed.\n     *\n     * Returns a string decoded from the read bytes.\n     */    async Ba(e) {\n        for (;this.buffer.length < e; ) {\n            await this.ka() && this.Na(\"Reached the end of bundle when more is expected.\");\n        }\n        const t = this.Ma.decode(this.buffer.slice(0, e));\n        // Update the internal buffer to drop the read json string.\n                return this.buffer = this.buffer.slice(e), t;\n    }\n    Na(e) {\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        throw this.Fa.cancel(), new Error(`Invalid bundle format: ${e}`);\n    }\n    /**\n     * Pulls more data from underlying stream to internal buffer.\n     * Returns a boolean indicating whether the stream is finished.\n     */    async ka() {\n        const e = await this.Fa.read();\n        if (!e.done) {\n            const t = new Uint8Array(this.buffer.length + e.value.length);\n            t.set(this.buffer), t.set(e.value, this.buffer.length), this.buffer = t;\n        }\n        return e.done;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nclass Transaction$2 {\n    constructor(e) {\n        this.datastore = e, \n        // The version of each document that was read during this transaction.\n        this.readVersions = new Map, this.mutations = [], this.committed = !1, \n        /**\n         * A deferred usage error that occurred previously in this transaction that\n         * will cause the transaction to fail once it actually commits.\n         */\n        this.lastWriteError = null, \n        /**\n         * Set of documents that have been written in the transaction.\n         *\n         * When there's more than one write to the same key in a transaction, any\n         * writes after the first are handled differently.\n         */\n        this.writtenDocs = new Set;\n    }\n    async lookup(e) {\n        if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new FirestoreError(v.INVALID_ARGUMENT, \"Firestore transactions require all reads to be executed before all writes.\");\n        const t = await async function __PRIVATE_invokeBatchGetDocumentsRpc(e, t) {\n            const n = __PRIVATE_debugCast(e), r = __PRIVATE_getEncodedDatabaseId(n.serializer) + \"/documents\", i = {\n                documents: t.map((e => __PRIVATE_toName(n.serializer, e)))\n            }, s = await n.yo(\"BatchGetDocuments\", r, i, t.length), o = new Map;\n            s.forEach((e => {\n                const t = __PRIVATE_fromBatchGetDocumentsResponse(n.serializer, e);\n                o.set(t.key.toString(), t);\n            }));\n            const _ = [];\n            return t.forEach((e => {\n                const t = o.get(e.toString());\n                __PRIVATE_hardAssert(!!t), _.push(t);\n            })), _;\n        }(this.datastore, e);\n        return t.forEach((e => this.recordVersion(e))), t;\n    }\n    set(e, t) {\n        this.write(t.toMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());\n    }\n    update(e, t) {\n        try {\n            this.write(t.toMutation(e, this.preconditionForUpdate(e)));\n        } catch (e) {\n            this.lastWriteError = e;\n        }\n        this.writtenDocs.add(e.toString());\n    }\n    delete(e) {\n        this.write(new __PRIVATE_DeleteMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());\n    }\n    async commit() {\n        if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;\n        const e = this.readVersions;\n        // For each mutation, note that the doc was written.\n                this.mutations.forEach((t => {\n            e.delete(t.key.toString());\n        })), \n        // For each document that was read but not written to, we want to perform\n        // a `verify` operation.\n        e.forEach(((e, t) => {\n            const n = DocumentKey.fromPath(t);\n            this.mutations.push(new __PRIVATE_VerifyMutation(n, this.precondition(n)));\n        })), await async function __PRIVATE_invokeCommitRpc(e, t) {\n            const n = __PRIVATE_debugCast(e), r = __PRIVATE_getEncodedDatabaseId(n.serializer) + \"/documents\", i = {\n                writes: t.map((e => toMutation(n.serializer, e)))\n            };\n            await n.Vo(\"Commit\", r, i);\n        }(this.datastore, this.mutations), this.committed = !0;\n    }\n    recordVersion(e) {\n        let t;\n        if (e.isFoundDocument()) t = e.version; else {\n            if (!e.isNoDocument()) throw fail();\n            // Represent a deleted doc using SnapshotVersion.min().\n            t = SnapshotVersion.min();\n        }\n        const n = this.readVersions.get(e.key.toString());\n        if (n) {\n            if (!t.isEqual(n)) \n            // This transaction will fail no matter what.\n            throw new FirestoreError(v.ABORTED, \"Document version changed between two reads.\");\n        } else this.readVersions.set(e.key.toString(), t);\n    }\n    /**\n     * Returns the version of this document when it was read in this transaction,\n     * as a precondition, or no precondition if it was not read.\n     */    precondition(e) {\n        const t = this.readVersions.get(e.toString());\n        return !this.writtenDocs.has(e.toString()) && t ? t.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(t) : Precondition.none();\n    }\n    /**\n     * Returns the precondition for a document if the operation is an update.\n     */    preconditionForUpdate(e) {\n        const t = this.readVersions.get(e.toString());\n        // The first time a document is written, we want to take into account the\n        // read time and existence\n                if (!this.writtenDocs.has(e.toString()) && t) {\n            if (t.isEqual(SnapshotVersion.min())) \n            // The document doesn't exist, so fail the transaction.\n            // This has to be validated locally because you can't send a\n            // precondition that a document does not exist without changing the\n            // semantics of the backend write to be an insert. This is the reverse\n            // of what we want, since we want to assert that the document doesn't\n            // exist but then send the update and have it fail. Since we can't\n            // express that to the backend, we have to validate locally.\n            // Note: this can change once we can send separate verify writes in the\n            // transaction.\n            throw new FirestoreError(v.INVALID_ARGUMENT, \"Can't update a document that doesn't exist.\");\n            // Document exists, base precondition on document update time.\n                        return Precondition.updateTime(t);\n        }\n        // Document was not read, so we just use the preconditions for a blind\n        // update.\n        return Precondition.exists(!0);\n    }\n    write(e) {\n        this.ensureCommitNotCalled(), this.mutations.push(e);\n    }\n    ensureCommitNotCalled() {}\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */ class __PRIVATE_TransactionRunner {\n    constructor(e, t, n, r, i) {\n        this.asyncQueue = e, this.datastore = t, this.options = n, this.updateFunction = r, \n        this.deferred = i, this.qa = n.maxAttempts, this.Ko = new __PRIVATE_ExponentialBackoff(this.asyncQueue, \"transaction_retry\" /* TimerId.TransactionRetry */);\n    }\n    /** Runs the transaction and sets the result on deferred. */    run() {\n        this.qa -= 1, this.Qa();\n    }\n    Qa() {\n        this.Ko.xo((async () => {\n            const e = new Transaction$2(this.datastore), t = this.Ka(e);\n            t && t.then((t => {\n                this.asyncQueue.enqueueAndForget((() => e.commit().then((() => {\n                    this.deferred.resolve(t);\n                })).catch((e => {\n                    this.$a(e);\n                }))));\n            })).catch((e => {\n                this.$a(e);\n            }));\n        }));\n    }\n    Ka(e) {\n        try {\n            const t = this.updateFunction(e);\n            return !__PRIVATE_isNullOrUndefined(t) && t.catch && t.then ? t : (this.deferred.reject(Error(\"Transaction callback must return a Promise\")), \n            null);\n        } catch (e) {\n            // Do not retry errors thrown by user provided updateFunction.\n            return this.deferred.reject(e), null;\n        }\n    }\n    $a(e) {\n        this.qa > 0 && this.Ua(e) ? (this.qa -= 1, this.asyncQueue.enqueueAndForget((() => (this.Qa(), \n        Promise.resolve())))) : this.deferred.reject(e);\n    }\n    Ua(e) {\n        if (\"FirebaseError\" === e.name) {\n            // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n            // non-matching document versions with ABORTED. These errors should be retried.\n            const t = e.code;\n            return \"aborted\" === t || \"failed-precondition\" === t || \"already-exists\" === t || !__PRIVATE_isPermanentError(t);\n        }\n        return !1;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the //\n * pieces of the client SDK architecture. It is responsible for creating the //\n * async queue that is shared by all of the other components in the system. //\n */\nclass FirestoreClient {\n    constructor(e, t, \n    /**\n     * Asynchronous queue responsible for all of our internal processing. When\n     * we get incoming work from the user (via public API) or the network\n     * (incoming GRPC messages), we should always schedule onto this queue.\n     * This ensures all of our work is properly serialized (e.g. we don't\n     * start processing a new operation while the previous one is waiting for\n     * an async I/O to complete).\n     */\n    n, r) {\n        this.authCredentials = e, this.appCheckCredentials = t, this.asyncQueue = n, this.databaseInfo = r, \n        this.user = User.UNAUTHENTICATED, this.clientId = __PRIVATE_AutoId.V(), this.authCredentialListener = () => Promise.resolve(), \n        this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async e => {\n            __PRIVATE_logDebug(\"FirestoreClient\", \"Received user=\", e.uid), await this.authCredentialListener(e), \n            this.user = e;\n        })), this.appCheckCredentials.start(n, (e => (__PRIVATE_logDebug(\"FirestoreClient\", \"Received new app check token=\", e), \n        this.appCheckCredentialListener(e, this.user))));\n    }\n    async getConfiguration() {\n        return {\n            asyncQueue: this.asyncQueue,\n            databaseInfo: this.databaseInfo,\n            clientId: this.clientId,\n            authCredentials: this.authCredentials,\n            appCheckCredentials: this.appCheckCredentials,\n            initialUser: this.user,\n            maxConcurrentLimboResolutions: 100\n        };\n    }\n    setCredentialChangeListener(e) {\n        this.authCredentialListener = e;\n    }\n    setAppCheckTokenChangeListener(e) {\n        this.appCheckCredentialListener = e;\n    }\n    /**\n     * Checks that the client has not been terminated. Ensures that other methods on //\n     * this class cannot be called after the client is terminated. //\n     */    verifyNotTerminated() {\n        if (this.asyncQueue.isShuttingDown) throw new FirestoreError(v.FAILED_PRECONDITION, \"The client has already been terminated.\");\n    }\n    terminate() {\n        this.asyncQueue.enterRestrictedMode();\n        const e = new __PRIVATE_Deferred;\n        return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {\n            try {\n                this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), \n                // The credentials provider must be terminated after shutting down the\n                // RemoteStore as it will prevent the RemoteStore from retrieving auth\n                // tokens.\n                this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), e.resolve();\n            } catch (t) {\n                const n = __PRIVATE_wrapInUserErrorIfRecoverable(t, \"Failed to shutdown persistence\");\n                e.reject(n);\n            }\n        })), e.promise;\n    }\n}\n\nasync function __PRIVATE_setOfflineComponentProvider(e, t) {\n    e.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(\"FirestoreClient\", \"Initializing OfflineComponentProvider\");\n    const n = await e.getConfiguration();\n    await t.initialize(n);\n    let r = n.initialUser;\n    e.setCredentialChangeListener((async e => {\n        r.isEqual(e) || (await __PRIVATE_localStoreHandleUserChange(t.localStore, e), r = e);\n    })), \n    // When a user calls clearPersistence() in one client, all other clients\n    // need to be terminated to allow the delete to succeed.\n    t.persistence.setDatabaseDeletedListener((() => e.terminate())), e._offlineComponents = t;\n}\n\nasync function __PRIVATE_setOnlineComponentProvider(e, t) {\n    e.asyncQueue.verifyOperationInProgress();\n    const n = await __PRIVATE_ensureOfflineComponents(e);\n    __PRIVATE_logDebug(\"FirestoreClient\", \"Initializing OnlineComponentProvider\");\n    const r = await e.getConfiguration();\n    await t.initialize(n, r), \n    // The CredentialChangeListener of the online component provider takes\n    // precedence over the offline component provider.\n    e.setCredentialChangeListener((e => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, e))), \n    e.setAppCheckTokenChangeListener(((e, n) => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, n))), \n    e._onlineComponents = t;\n}\n\n/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */ function __PRIVATE_canFallbackFromIndexedDbError(e) {\n    return \"FirebaseError\" === e.name ? e.code === v.FAILED_PRECONDITION || e.code === v.UNIMPLEMENTED : !(\"undefined\" != typeof DOMException && e instanceof DOMException) || (\n    // When the browser is out of quota we could get either quota exceeded\n    // or an aborted error depending on whether the error happened during\n    // schema migration.\n    22 === e.code || 20 === e.code || \n    // Firefox Private Browsing mode disables IndexedDb and returns\n    // INVALID_STATE for any usage.\n    11 === e.code);\n}\n\nasync function __PRIVATE_ensureOfflineComponents(e) {\n    if (!e._offlineComponents) if (e._uninitializedComponentsProvider) {\n        __PRIVATE_logDebug(\"FirestoreClient\", \"Using user provided OfflineComponentProvider\");\n        try {\n            await __PRIVATE_setOfflineComponentProvider(e, e._uninitializedComponentsProvider._offline);\n        } catch (t) {\n            const n = t;\n            if (!__PRIVATE_canFallbackFromIndexedDbError(n)) throw n;\n            __PRIVATE_logWarn(\"Error using user provided cache. Falling back to memory cache: \" + n), \n            await __PRIVATE_setOfflineComponentProvider(e, new MemoryOfflineComponentProvider);\n        }\n    } else __PRIVATE_logDebug(\"FirestoreClient\", \"Using default OfflineComponentProvider\"), \n    await __PRIVATE_setOfflineComponentProvider(e, new MemoryOfflineComponentProvider);\n    return e._offlineComponents;\n}\n\nasync function __PRIVATE_ensureOnlineComponents(e) {\n    return e._onlineComponents || (e._uninitializedComponentsProvider ? (__PRIVATE_logDebug(\"FirestoreClient\", \"Using user provided OnlineComponentProvider\"), \n    await __PRIVATE_setOnlineComponentProvider(e, e._uninitializedComponentsProvider._online)) : (__PRIVATE_logDebug(\"FirestoreClient\", \"Using default OnlineComponentProvider\"), \n    await __PRIVATE_setOnlineComponentProvider(e, new OnlineComponentProvider))), e._onlineComponents;\n}\n\nfunction __PRIVATE_getPersistence(e) {\n    return __PRIVATE_ensureOfflineComponents(e).then((e => e.persistence));\n}\n\nfunction __PRIVATE_getLocalStore(e) {\n    return __PRIVATE_ensureOfflineComponents(e).then((e => e.localStore));\n}\n\nfunction __PRIVATE_getRemoteStore(e) {\n    return __PRIVATE_ensureOnlineComponents(e).then((e => e.remoteStore));\n}\n\nfunction __PRIVATE_getSyncEngine(e) {\n    return __PRIVATE_ensureOnlineComponents(e).then((e => e.syncEngine));\n}\n\nfunction __PRIVATE_getDatastore(e) {\n    return __PRIVATE_ensureOnlineComponents(e).then((e => e.datastore));\n}\n\nasync function __PRIVATE_getEventManager(e) {\n    const t = await __PRIVATE_ensureOnlineComponents(e), n = t.eventManager;\n    return n.onListen = __PRIVATE_syncEngineListen.bind(null, t.syncEngine), n.onUnlisten = __PRIVATE_syncEngineUnlisten.bind(null, t.syncEngine), \n    n;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */ function __PRIVATE_firestoreClientEnableNetwork(e) {\n    return e.asyncQueue.enqueue((async () => {\n        const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);\n        return t.setNetworkEnabled(!0), function __PRIVATE_remoteStoreEnableNetwork(e) {\n            const t = __PRIVATE_debugCast(e);\n            return t.y_.delete(0 /* OfflineCause.UserDisabled */), __PRIVATE_enableNetworkInternal(t);\n        }(n);\n    }));\n}\n\n/** Disables the network connection. Pending operations will not complete. */ function __PRIVATE_firestoreClientDisableNetwork(e) {\n    return e.asyncQueue.enqueue((async () => {\n        const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);\n        return t.setNetworkEnabled(!1), async function __PRIVATE_remoteStoreDisableNetwork(e) {\n            const t = __PRIVATE_debugCast(e);\n            t.y_.add(0 /* OfflineCause.UserDisabled */), await __PRIVATE_disableNetworkInternal(t), \n            // Set the OnlineState to Offline so get()s return from cache, etc.\n            t.b_.set(\"Offline\" /* OnlineState.Offline */);\n        }(n);\n    }));\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */ function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e, t) {\n    const n = new __PRIVATE_Deferred;\n    return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_readDocumentFromCache(e, t, n) {\n        try {\n            const r = await function __PRIVATE_localStoreReadDocument(e, t) {\n                const n = __PRIVATE_debugCast(e);\n                return n.persistence.runTransaction(\"read document\", \"readonly\", (e => n.localDocuments.getDocument(e, t)));\n            }(e, t);\n            r.isFoundDocument() ? n.resolve(r) : r.isNoDocument() ? n.resolve(null) : n.reject(new FirestoreError(v.UNAVAILABLE, \"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)\"));\n        } catch (e) {\n            const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to get document '${t} from cache`);\n            n.reject(r);\n        }\n    }\n    /**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise;\n}\n\nfunction __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e, t, n = {}) {\n    const r = new __PRIVATE_Deferred;\n    return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_readDocumentViaSnapshotListener(e, t, n, r, i) {\n        const s = new __PRIVATE_AsyncObserver({\n            next: s => {\n                // Remove query first before passing event to user to avoid\n                // user actions affecting the now stale query.\n                t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o)));\n                const _ = s.docs.has(n);\n                !_ && s.fromCache ? \n                // TODO(dimond): If we're online and the document doesn't\n                // exist then we resolve with a doc.exists set to false. If\n                // we're offline however, we reject the Promise in this\n                // case. Two options: 1) Cache the negative response from\n                // the server so we can deliver that even when you're\n                // offline 2) Actually reject the Promise in the online case\n                // if the document doesn't exist.\n                i.reject(new FirestoreError(v.UNAVAILABLE, \"Failed to get document because the client is offline.\")) : _ && s.fromCache && r && \"server\" === r.source ? i.reject(new FirestoreError(v.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to \"server\" to retrieve the cached document.)')) : i.resolve(s);\n            },\n            error: e => i.reject(e)\n        }), o = new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(n.path), s, {\n            includeMetadataChanges: !0,\n            W_: !0\n        });\n        return __PRIVATE_eventManagerListen(e, o);\n    }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise;\n}\n\nfunction __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e, t) {\n    const n = new __PRIVATE_Deferred;\n    return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_executeQueryFromCache(e, t, n) {\n        try {\n            const r = await __PRIVATE_localStoreExecuteQuery(e, t, \n            /* usePreviousResults= */ !0), i = new __PRIVATE_View(t, r.ss), s = i.sa(r.documents), o = i.applyChanges(s, \n            /* updateLimboDocuments= */ !1);\n            n.resolve(o.snapshot);\n        } catch (e) {\n            const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to execute query '${t} against cache`);\n            n.reject(r);\n        }\n    }\n    /**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise;\n}\n\nfunction __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e, t, n = {}) {\n    const r = new __PRIVATE_Deferred;\n    return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_executeQueryViaSnapshotListener(e, t, n, r, i) {\n        const s = new __PRIVATE_AsyncObserver({\n            next: n => {\n                // Remove query first before passing event to user to avoid\n                // user actions affecting the now stale query.\n                t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))), n.fromCache && \"server\" === r.source ? i.reject(new FirestoreError(v.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to \"server\" to retrieve the cached documents.)')) : i.resolve(n);\n            },\n            error: e => i.reject(e)\n        }), o = new __PRIVATE_QueryListener(n, s, {\n            includeMetadataChanges: !0,\n            W_: !0\n        });\n        return __PRIVATE_eventManagerListen(e, o);\n    }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise;\n}\n\nfunction __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e, t) {\n    const n = new __PRIVATE_AsyncObserver(t);\n    return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_addSnapshotsInSyncListener(e, t) {\n        __PRIVATE_debugCast(e).O_.add(t), \n        // Immediately fire an initial event, indicating all existing listeners\n        // are in-sync.\n        t.next();\n    }(await __PRIVATE_getEventManager(e), n))), () => {\n        n.Ca(), e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_removeSnapshotsInSyncListener(e, t) {\n            __PRIVATE_debugCast(e).O_.delete(t);\n        }(await __PRIVATE_getEventManager(e), n)));\n    };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */ function __PRIVATE_firestoreClientLoadBundle(e, t, n, r) {\n    const i = function __PRIVATE_createBundleReader(e, t) {\n        let n;\n        n = \"string\" == typeof e ? __PRIVATE_newTextEncoder().encode(e) : e;\n        return function __PRIVATE_newBundleReader(e, t) {\n            return new __PRIVATE_BundleReaderImpl(e, t);\n        }(function __PRIVATE_toByteStreamReader(e, t) {\n            if (e instanceof Uint8Array) return __PRIVATE_toByteStreamReaderHelper(e, t);\n            if (e instanceof ArrayBuffer) return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e), t);\n            if (e instanceof ReadableStream) return e.getReader();\n            throw new Error(\"Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream\");\n        }(n), t);\n    }(n, __PRIVATE_newSerializer(t));\n    e.asyncQueue.enqueueAndForget((async () => {\n        __PRIVATE_syncEngineLoadBundle(await __PRIVATE_getSyncEngine(e), i, r);\n    }));\n}\n\nfunction __PRIVATE_firestoreClientGetNamedQuery(e, t) {\n    return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreGetNamedQuery(e, t) {\n        const n = __PRIVATE_debugCast(e);\n        return n.persistence.runTransaction(\"Get named query\", \"readonly\", (e => n.Qr.getNamedQuery(e, t)));\n    }(await __PRIVATE_getLocalStore(e), t)));\n}\n\nfunction __PRIVATE_firestoreClientSetIndexConfiguration(e, t) {\n    return e.asyncQueue.enqueue((async () => async function __PRIVATE_localStoreConfigureFieldIndexes(e, t) {\n        const n = __PRIVATE_debugCast(e), r = n.indexManager, i = [];\n        return n.persistence.runTransaction(\"Configure indexes\", \"readwrite\", (e => r.getFieldIndexes(e).next((n => \n        /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n        /**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n        function __PRIVATE_diffArrays(e, t, n, r, i) {\n            e = [ ...e ], t = [ ...t ], e.sort(n), t.sort(n);\n            const s = e.length, o = t.length;\n            let _ = 0, a = 0;\n            for (;_ < o && a < s; ) {\n                const s = n(e[a], t[_]);\n                s < 0 ? \n                // The element was removed if the next element in our ordered\n                // walkthrough is only in `before`.\n                i(e[a++]) : s > 0 ? \n                // The element was added if the next element in our ordered walkthrough\n                // is only in `after`.\n                r(t[_++]) : (_++, a++);\n            }\n            for (;_ < o; ) r(t[_++]);\n            for (;a < s; ) i(e[a++]);\n        }(n, t, __PRIVATE_fieldIndexSemanticComparator, (t => {\n            i.push(r.addFieldIndex(e, t));\n        }), (t => {\n            i.push(r.deleteFieldIndex(e, t));\n        })))).next((() => PersistencePromise.waitFor(i)))));\n    }\n    /**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n    // The format of the LocalStorage key that stores the client state is:\n    //     firestore_clients_<persistence_prefix>_<instance_key>\n    (await __PRIVATE_getLocalStore(e), t)));\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nfunction __PRIVATE_cloneLongPollingOptions(e) {\n    const t = {};\n    return void 0 !== e.timeoutSeconds && (t.timeoutSeconds = e.timeoutSeconds), t;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const fe = new Map;\n\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction __PRIVATE_validateNonEmptyArgument(e, t, n) {\n    if (!n) throw new FirestoreError(v.INVALID_ARGUMENT, `Function ${e}() cannot be called with an empty ${t}.`);\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */ function __PRIVATE_validateIsNotUsedTogether(e, t, n, r) {\n    if (!0 === t && !0 === r) throw new FirestoreError(v.INVALID_ARGUMENT, `${e} and ${n} cannot be used together.`);\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */ function __PRIVATE_validateDocumentPath(e) {\n    if (!DocumentKey.isDocumentKey(e)) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`);\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */ function __PRIVATE_validateCollectionPath(e) {\n    if (DocumentKey.isDocumentKey(e)) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`);\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\n/** Returns a string describing the type / value of the provided input. */\nfunction __PRIVATE_valueDescription(e) {\n    if (void 0 === e) return \"undefined\";\n    if (null === e) return \"null\";\n    if (\"string\" == typeof e) return e.length > 20 && (e = `${e.substring(0, 20)}...`), \n    JSON.stringify(e);\n    if (\"number\" == typeof e || \"boolean\" == typeof e) return \"\" + e;\n    if (\"object\" == typeof e) {\n        if (e instanceof Array) return \"an array\";\n        {\n            const t = \n            /** try to get the constructor name for an object. */\n            function __PRIVATE_tryGetCustomObjectType(e) {\n                if (e.constructor) return e.constructor.name;\n                return null;\n            }\n            /**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if  `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */ (e);\n            return t ? `a custom ${t} object` : \"an object\";\n        }\n    }\n    return \"function\" == typeof e ? \"a function\" : fail();\n}\n\nfunction __PRIVATE_cast(e, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nt) {\n    if (\"_delegate\" in e && (\n    // Unwrap Compat types\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    e = e._delegate), !(e instanceof t)) {\n        if (t.name === e.constructor.name) throw new FirestoreError(v.INVALID_ARGUMENT, \"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?\");\n        {\n            const n = __PRIVATE_valueDescription(e);\n            throw new FirestoreError(v.INVALID_ARGUMENT, `Expected type '${t.name}', but it was: ${n}`);\n        }\n    }\n    return e;\n}\n\nfunction __PRIVATE_validatePositiveNumber(e, t) {\n    if (t <= 0) throw new FirestoreError(v.INVALID_ARGUMENT, `Function ${e}() requires a positive number, but it was: ${t}.`);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// settings() defaults:\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nclass FirestoreSettingsImpl {\n    constructor(e) {\n        var t, n;\n        if (void 0 === e.host) {\n            if (void 0 !== e.ssl) throw new FirestoreError(v.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n            this.host = \"firestore.googleapis.com\", this.ssl = true;\n        } else this.host = e.host, this.ssl = null === (t = e.ssl) || void 0 === t || t;\n        if (this.credentials = e.credentials, this.ignoreUndefinedProperties = !!e.ignoreUndefinedProperties, \n        this.localCache = e.localCache, void 0 === e.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {\n            if (-1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new FirestoreError(v.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n            this.cacheSizeBytes = e.cacheSizeBytes;\n        }\n        __PRIVATE_validateIsNotUsedTogether(\"experimentalForceLongPolling\", e.experimentalForceLongPolling, \"experimentalAutoDetectLongPolling\", e.experimentalAutoDetectLongPolling), \n        this.experimentalForceLongPolling = !!e.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === e.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : \n        // For backwards compatibility, coerce the value to boolean even though\n        // the TypeScript compiler has narrowed the type to boolean already.\n        // noinspection PointlessBooleanExpressionJS\n        this.experimentalAutoDetectLongPolling = !!e.experimentalAutoDetectLongPolling, \n        this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(null !== (n = e.experimentalLongPollingOptions) && void 0 !== n ? n : {}), \n        function __PRIVATE_validateLongPollingOptions(e) {\n            if (void 0 !== e.timeoutSeconds) {\n                if (isNaN(e.timeoutSeconds)) throw new FirestoreError(v.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);\n                if (e.timeoutSeconds < 5) throw new FirestoreError(v.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);\n                if (e.timeoutSeconds > 30) throw new FirestoreError(v.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`);\n            }\n        }\n        /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n        /**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!e.useFetchStreams;\n    }\n    isEqual(e) {\n        return this.host === e.host && this.ssl === e.ssl && this.credentials === e.credentials && this.cacheSizeBytes === e.cacheSizeBytes && this.experimentalForceLongPolling === e.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === e.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(e, t) {\n            return e.timeoutSeconds === t.timeoutSeconds;\n        }(this.experimentalLongPollingOptions, e.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e.ignoreUndefinedProperties && this.useFetchStreams === e.useFetchStreams;\n    }\n}\n\nclass Firestore$1 {\n    /** @hideconstructor */\n    constructor(e, t, n, r) {\n        this._authCredentials = e, this._appCheckCredentials = t, this._databaseId = n, \n        this._app = r, \n        /**\n         * Whether it's a Firestore or Firestore Lite instance.\n         */\n        this.type = \"firestore-lite\", this._persistenceKey = \"(lite)\", this._settings = new FirestoreSettingsImpl({}), \n        this._settingsFrozen = !1;\n    }\n    /**\n     * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n     * instance.\n     */    get app() {\n        if (!this._app) throw new FirestoreError(v.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is not available\");\n        return this._app;\n    }\n    get _initialized() {\n        return this._settingsFrozen;\n    }\n    get _terminated() {\n        return void 0 !== this._terminateTask;\n    }\n    _setSettings(e) {\n        if (this._settingsFrozen) throw new FirestoreError(v.FAILED_PRECONDITION, \"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.\");\n        this._settings = new FirestoreSettingsImpl(e), void 0 !== e.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(e) {\n            if (!e) return new __PRIVATE_EmptyAuthCredentialsProvider;\n            switch (e.type) {\n              case \"firstParty\":\n                return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex || \"0\", e.iamToken || null, e.authTokenFactory || null);\n\n              case \"provider\":\n                return e.client;\n\n              default:\n                throw new FirestoreError(v.INVALID_ARGUMENT, \"makeAuthCredentialsProvider failed due to invalid credential type\");\n            }\n        }(e.credentials));\n    }\n    _getSettings() {\n        return this._settings;\n    }\n    _freezeSettings() {\n        return this._settingsFrozen = !0, this._settings;\n    }\n    _delete() {\n        return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;\n    }\n    /** Returns a JSON-serializable representation of this `Firestore` instance. */    toJSON() {\n        return {\n            app: this._app,\n            databaseId: this._databaseId,\n            settings: this._settings\n        };\n    }\n    /**\n     * Terminates all components used by this client. Subclasses can override\n     * this method to clean up their own dependencies, but must also call this\n     * method.\n     *\n     * Only ever called once.\n     */    _terminate() {\n        /**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\n        return function __PRIVATE_removeComponents(e) {\n            const t = fe.get(e);\n            t && (__PRIVATE_logDebug(\"ComponentProvider\", \"Removing Datastore\"), fe.delete(e), \n            t.terminate());\n        }(this), Promise.resolve();\n    }\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */ function connectFirestoreEmulator(e, t, n, r = {}) {\n    var i;\n    const s = (e = __PRIVATE_cast(e, Firestore$1))._getSettings(), o = `${t}:${n}`;\n    if (\"firestore.googleapis.com\" !== s.host && s.host !== o && __PRIVATE_logWarn(\"Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.\"), \n    e._setSettings(Object.assign(Object.assign({}, s), {\n        host: o,\n        ssl: !1\n    })), r.mockUserToken) {\n        let t, n;\n        if (\"string\" == typeof r.mockUserToken) t = r.mockUserToken, n = User.MOCK_USER; else {\n            // Let createMockUserToken validate first (catches common mistakes like\n            // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n            t = createMockUserToken(r.mockUserToken, null === (i = e._app) || void 0 === i ? void 0 : i.options.projectId);\n            const s = r.mockUserToken.sub || r.mockUserToken.user_id;\n            if (!s) throw new FirestoreError(v.INVALID_ARGUMENT, \"mockUserToken must contain 'sub' or 'user_id' field!\");\n            n = new User(s);\n        }\n        e._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t, n));\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */ class Query {\n    // This is the lite version of the Query class in the main SDK.\n    /** @hideconstructor protected */\n    constructor(e, \n    /**\n     * If provided, the `FirestoreDataConverter` associated with this instance.\n     */\n    t, n) {\n        this.converter = t, this._query = n, \n        /** The type of this Firestore reference. */\n        this.type = \"query\", this.firestore = e;\n    }\n    withConverter(e) {\n        return new Query(this.firestore, e, this._query);\n    }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */ class DocumentReference {\n    /** @hideconstructor */\n    constructor(e, \n    /**\n     * If provided, the `FirestoreDataConverter` associated with this instance.\n     */\n    t, n) {\n        this.converter = t, this._key = n, \n        /** The type of this Firestore reference. */\n        this.type = \"document\", this.firestore = e;\n    }\n    get _path() {\n        return this._key.path;\n    }\n    /**\n     * The document's identifier within its collection.\n     */    get id() {\n        return this._key.path.lastSegment();\n    }\n    /**\n     * A string representing the path of the referenced document (relative\n     * to the root of the database).\n     */    get path() {\n        return this._key.path.canonicalString();\n    }\n    /**\n     * The collection this `DocumentReference` belongs to.\n     */    get parent() {\n        return new CollectionReference(this.firestore, this.converter, this._key.path.popLast());\n    }\n    withConverter(e) {\n        return new DocumentReference(this.firestore, e, this._key);\n    }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */ class CollectionReference extends Query {\n    /** @hideconstructor */\n    constructor(e, t, n) {\n        super(e, t, __PRIVATE_newQueryForPath(n)), this._path = n, \n        /** The type of this Firestore reference. */\n        this.type = \"collection\";\n    }\n    /** The collection's identifier. */    get id() {\n        return this._query.path.lastSegment();\n    }\n    /**\n     * A string representing the path of the referenced collection (relative\n     * to the root of the database).\n     */    get path() {\n        return this._query.path.canonicalString();\n    }\n    /**\n     * A reference to the containing `DocumentReference` if this is a\n     * subcollection. If this isn't a subcollection, the reference is null.\n     */    get parent() {\n        const e = this._path.popLast();\n        return e.isEmpty() ? null : new DocumentReference(this.firestore, \n        /* converter= */ null, new DocumentKey(e));\n    }\n    withConverter(e) {\n        return new CollectionReference(this.firestore, e, this._path);\n    }\n}\n\nfunction collection(e, t, ...n) {\n    if (e = getModularInstance(e), __PRIVATE_validateNonEmptyArgument(\"collection\", \"path\", t), e instanceof Firestore$1) {\n        const r = ResourcePath.fromString(t, ...n);\n        return __PRIVATE_validateCollectionPath(r), new CollectionReference(e, /* converter= */ null, r);\n    }\n    {\n        if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(v.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n        const r = e._path.child(ResourcePath.fromString(t, ...n));\n        return __PRIVATE_validateCollectionPath(r), new CollectionReference(e.firestore, \n        /* converter= */ null, r);\n    }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */ function collectionGroup(e, t) {\n    if (e = __PRIVATE_cast(e, Firestore$1), __PRIVATE_validateNonEmptyArgument(\"collectionGroup\", \"collection id\", t), \n    t.indexOf(\"/\") >= 0) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);\n    return new Query(e, \n    /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(e) {\n        return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), e);\n    }(t));\n}\n\nfunction doc(e, t, ...n) {\n    if (e = getModularInstance(e), \n    // We allow omission of 'pathString' but explicitly prohibit passing in both\n    // 'undefined' and 'null'.\n    1 === arguments.length && (t = __PRIVATE_AutoId.V()), __PRIVATE_validateNonEmptyArgument(\"doc\", \"path\", t), \n    e instanceof Firestore$1) {\n        const r = ResourcePath.fromString(t, ...n);\n        return __PRIVATE_validateDocumentPath(r), new DocumentReference(e, \n        /* converter= */ null, new DocumentKey(r));\n    }\n    {\n        if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(v.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n        const r = e._path.child(ResourcePath.fromString(t, ...n));\n        return __PRIVATE_validateDocumentPath(r), new DocumentReference(e.firestore, e instanceof CollectionReference ? e.converter : null, new DocumentKey(r));\n    }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function refEqual(e, t) {\n    return e = getModularInstance(e), t = getModularInstance(t), (e instanceof DocumentReference || e instanceof CollectionReference) && (t instanceof DocumentReference || t instanceof CollectionReference) && (e.firestore === t.firestore && e.path === t.path && e.converter === t.converter);\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function queryEqual(e, t) {\n    return e = getModularInstance(e), t = getModularInstance(t), e instanceof Query && t instanceof Query && (e.firestore === t.firestore && __PRIVATE_queryEquals(e._query, t._query) && e.converter === t.converter);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class __PRIVATE_AsyncQueueImpl {\n    constructor() {\n        // The last promise in the queue.\n        this.Wa = Promise.resolve(), \n        // A list of retryable operations. Retryable operations are run in order and\n        // retried with backoff.\n        this.Ga = [], \n        // Is this AsyncQueue being shut down? Once it is set to true, it will not\n        // be changed again.\n        this.za = !1, \n        // Operations scheduled to be queued in the future. Operations are\n        // automatically removed after they are run or canceled.\n        this.ja = [], \n        // visible for testing\n        this.Ha = null, \n        // Flag set while there's an outstanding AsyncQueue operation, used for\n        // assertion sanity-checks.\n        this.Ja = !1, \n        // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n        this.Ya = !1, \n        // List of TimerIds to fast-forward delays for.\n        this.Za = [], \n        // Backoff timer used to schedule retries for retryable operations\n        this.Ko = new __PRIVATE_ExponentialBackoff(this, \"async_queue_retry\" /* TimerId.AsyncQueueRetry */), \n        // Visibility handler that triggers an immediate retry of all retryable\n        // operations. Meant to speed up recovery when we regain file system access\n        // after page comes into foreground.\n        this.Xa = () => {\n            const e = getDocument();\n            e && __PRIVATE_logDebug(\"AsyncQueue\", \"Visibility state changed to \" + e.visibilityState), \n            this.Ko.No();\n        };\n        const e = getDocument();\n        e && \"function\" == typeof e.addEventListener && e.addEventListener(\"visibilitychange\", this.Xa);\n    }\n    get isShuttingDown() {\n        return this.za;\n    }\n    /**\n     * Adds a new operation to the queue without waiting for it to complete (i.e.\n     * we ignore the Promise result).\n     */    enqueueAndForget(e) {\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        this.enqueue(e);\n    }\n    enqueueAndForgetEvenWhileRestricted(e) {\n        this.eu(), \n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        this.tu(e);\n    }\n    enterRestrictedMode(e) {\n        if (!this.za) {\n            this.za = !0, this.Ya = e || !1;\n            const t = getDocument();\n            t && \"function\" == typeof t.removeEventListener && t.removeEventListener(\"visibilitychange\", this.Xa);\n        }\n    }\n    enqueue(e) {\n        if (this.eu(), this.za) \n        // Return a Promise which never resolves.\n        return new Promise((() => {}));\n        // Create a deferred Promise that we can return to the callee. This\n        // allows us to return a \"hanging Promise\" only to the callee and still\n        // advance the queue even when the operation is not run.\n                const t = new __PRIVATE_Deferred;\n        return this.tu((() => this.za && this.Ya ? Promise.resolve() : (e().then(t.resolve, t.reject), \n        t.promise))).then((() => t.promise));\n    }\n    enqueueRetryable(e) {\n        this.enqueueAndForget((() => (this.Ga.push(e), this.nu())));\n    }\n    /**\n     * Runs the next operation from the retryable queue. If the operation fails,\n     * reschedules with backoff.\n     */    async nu() {\n        if (0 !== this.Ga.length) {\n            try {\n                await this.Ga[0](), this.Ga.shift(), this.Ko.reset();\n            } catch (e) {\n                if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;\n // Failure will be handled by AsyncQueue\n                                __PRIVATE_logDebug(\"AsyncQueue\", \"Operation failed with retryable error: \" + e);\n            }\n            this.Ga.length > 0 && \n            // If there are additional operations, we re-schedule `retryNextOp()`.\n            // This is necessary to run retryable operations that failed during\n            // their initial attempt since we don't know whether they are already\n            // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n            // needs to  be re-run, we will run `op1`, `op1`, `op2` using the\n            // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n            // call scheduled here.\n            // Since `backoffAndRun()` cancels an existing backoff and schedules a\n            // new backoff on every call, there is only ever a single additional\n            // operation in the queue.\n            this.Ko.xo((() => this.nu()));\n        }\n    }\n    tu(e) {\n        const t = this.Wa.then((() => (this.Ja = !0, e().catch((e => {\n            this.Ha = e, this.Ja = !1;\n            const t = \n            /**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\n            function __PRIVATE_getMessageOrStack(e) {\n                let t = e.message || \"\";\n                e.stack && (t = e.stack.includes(e.message) ? e.stack : e.message + \"\\n\" + e.stack);\n                return t;\n            }\n            /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (e);\n            // Re-throw the error so that this.tail becomes a rejected Promise and\n            // all further attempts to chain (via .then) will just short-circuit\n            // and return the rejected Promise.\n            throw __PRIVATE_logError(\"INTERNAL UNHANDLED ERROR: \", t), e;\n        })).then((e => (this.Ja = !1, e))))));\n        return this.Wa = t, t;\n    }\n    enqueueAfterDelay(e, t, n) {\n        this.eu(), \n        // Fast-forward delays for timerIds that have been overriden.\n        this.Za.indexOf(e) > -1 && (t = 0);\n        const r = DelayedOperation.createAndSchedule(this, e, t, n, (e => this.ru(e)));\n        return this.ja.push(r), r;\n    }\n    eu() {\n        this.Ha && fail();\n    }\n    verifyOperationInProgress() {}\n    /**\n     * Waits until all currently queued tasks are finished executing. Delayed\n     * operations are not run.\n     */    async iu() {\n        // Operations in the queue prior to draining may have enqueued additional\n        // operations. Keep draining the queue until the tail is no longer advanced,\n        // which indicates that no more new operations were enqueued and that all\n        // operations were executed.\n        let e;\n        do {\n            e = this.Wa, await e;\n        } while (e !== this.Wa);\n    }\n    /**\n     * For Tests: Determine if a delayed operation with a particular TimerId\n     * exists.\n     */    su(e) {\n        for (const t of this.ja) if (t.timerId === e) return !0;\n        return !1;\n    }\n    /**\n     * For Tests: Runs some or all delayed operations early.\n     *\n     * @param lastTimerId - Delayed operations up to and including this TimerId\n     * will be drained. Pass TimerId.All to run all delayed operations.\n     * @returns a Promise that resolves once all operations have been run.\n     */    ou(e) {\n        // Note that draining may generate more delayed ops, so we do that first.\n        return this.iu().then((() => {\n            // Run ops in the same order they'd run if they ran naturally.\n            this.ja.sort(((e, t) => e.targetTimeMs - t.targetTimeMs));\n            for (const t of this.ja) if (t.skipDelay(), \"all\" /* TimerId.All */ !== e && t.timerId === e) break;\n            return this.iu();\n        }));\n    }\n    /**\n     * For Tests: Skip all subsequent delays for a timer id.\n     */    _u(e) {\n        this.Za.push(e);\n    }\n    /** Called once a DelayedOperation is run or canceled. */    ru(e) {\n        // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n        const t = this.ja.indexOf(e);\n        this.ja.splice(t, 1);\n    }\n}\n\nfunction __PRIVATE_isPartialObserver(e) {\n    /**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\n    return function __PRIVATE_implementsAnyMethods(e, t) {\n        if (\"object\" != typeof e || null === e) return !1;\n        const n = e;\n        for (const e of t) if (e in n && \"function\" == typeof n[e]) return !0;\n        return !1;\n    }\n    /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n    /**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise<LoadBundleTaskProgress>`.\n */ (e, [ \"next\", \"error\", \"complete\" ]);\n}\n\nclass LoadBundleTask {\n    constructor() {\n        this._progressObserver = {}, this._taskCompletionResolver = new __PRIVATE_Deferred, \n        this._lastProgress = {\n            taskState: \"Running\",\n            totalBytes: 0,\n            totalDocuments: 0,\n            bytesLoaded: 0,\n            documentsLoaded: 0\n        };\n    }\n    /**\n     * Registers functions to listen to bundle loading progress events.\n     * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n     *   each time a Firestore document is loaded from the bundle.\n     * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n     *   error, and there should be no more updates after this.\n     * @param complete - Called when the loading task is complete.\n     */    onProgress(e, t, n) {\n        this._progressObserver = {\n            next: e,\n            error: t,\n            complete: n\n        };\n    }\n    /**\n     * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.\n     *\n     * @param onRejected - Called when an error occurs during bundle loading.\n     */    catch(e) {\n        return this._taskCompletionResolver.promise.catch(e);\n    }\n    /**\n     * Implements the `Promise<LoadBundleTaskProgress>.then` interface.\n     *\n     * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n     *   The update will always have its `taskState` set to `\"Success\"`.\n     * @param onRejected - Called when an error occurs during bundle loading.\n     */    then(e, t) {\n        return this._taskCompletionResolver.promise.then(e, t);\n    }\n    /**\n     * Notifies all observers that bundle loading has completed, with a provided\n     * `LoadBundleTaskProgress` object.\n     *\n     * @private\n     */    _completeWith(e) {\n        this._updateProgress(e), this._progressObserver.complete && this._progressObserver.complete(), \n        this._taskCompletionResolver.resolve(e);\n    }\n    /**\n     * Notifies all observers that bundle loading has failed, with a provided\n     * `Error` as the reason.\n     *\n     * @private\n     */    _failWith(e) {\n        this._lastProgress.taskState = \"Error\", this._progressObserver.next && this._progressObserver.next(this._lastProgress), \n        this._progressObserver.error && this._progressObserver.error(e), this._taskCompletionResolver.reject(e);\n    }\n    /**\n     * Notifies a progress update of loading a bundle.\n     * @param progress - The new progress.\n     *\n     * @private\n     */    _updateProgress(e) {\n        this._lastProgress = e, this._progressObserver.next && this._progressObserver.next(e);\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * {@link Firestore} instance.\n */ const ge = -1;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ class Firestore extends Firestore$1 {\n    /** @hideconstructor */\n    constructor(e, t, n, r) {\n        super(e, t, n, r), \n        /**\n         * Whether it's a {@link Firestore} or Firestore Lite instance.\n         */\n        this.type = \"firestore\", this._queue = function __PRIVATE_newAsyncQueue() {\n            return new __PRIVATE_AsyncQueueImpl;\n        }(), this._persistenceKey = (null == r ? void 0 : r.name) || \"[DEFAULT]\";\n    }\n    _terminate() {\n        return this._firestoreClient || \n        // The client must be initialized to ensure that all subsequent API\n        // usage throws an exception.\n        __PRIVATE_configureFirestore(this), this._firestoreClient.terminate();\n    }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized {@link Firestore} instance.\n */ function initializeFirestore(e, t, n) {\n    n || (n = \"(default)\");\n    const r = _getProvider(e, \"firestore\");\n    if (r.isInitialized(n)) {\n        const e = r.getImmediate({\n            identifier: n\n        }), i = r.getOptions(n);\n        if (deepEqual(i, t)) return e;\n        throw new FirestoreError(v.FAILED_PRECONDITION, \"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.\");\n    }\n    if (void 0 !== t.cacheSizeBytes && void 0 !== t.localCache) throw new FirestoreError(v.INVALID_ARGUMENT, \"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object\");\n    if (void 0 !== t.cacheSizeBytes && -1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new FirestoreError(v.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n    return r.initialize({\n        options: t,\n        instanceIdentifier: n\n    });\n}\n\nfunction getFirestore(t, n) {\n    const r = \"object\" == typeof t ? t : getApp(), i = \"string\" == typeof t ? t : n || \"(default)\", s = _getProvider(r, \"firestore\").getImmediate({\n        identifier: i\n    });\n    if (!s._initialized) {\n        const e = getDefaultEmulatorHostnameAndPort(\"firestore\");\n        e && connectFirestoreEmulator(s, ...e);\n    }\n    return s;\n}\n\n/**\n * @internal\n */ function ensureFirestoreConfigured(e) {\n    return e._firestoreClient || __PRIVATE_configureFirestore(e), e._firestoreClient.verifyNotTerminated(), \n    e._firestoreClient;\n}\n\nfunction __PRIVATE_configureFirestore(e) {\n    var t, n, r;\n    const i = e._freezeSettings(), s = function __PRIVATE_makeDatabaseInfo(e, t, n, r) {\n        return new DatabaseInfo(e, t, n, r.host, r.ssl, r.experimentalForceLongPolling, r.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(r.experimentalLongPollingOptions), r.useFetchStreams);\n    }(e._databaseId, (null === (t = e._app) || void 0 === t ? void 0 : t.options.appId) || \"\", e._persistenceKey, i);\n    e._firestoreClient = new FirestoreClient(e._authCredentials, e._appCheckCredentials, e._queue, s), \n    (null === (n = i.localCache) || void 0 === n ? void 0 : n._offlineComponentProvider) && (null === (r = i.localCache) || void 0 === r ? void 0 : r._onlineComponentProvider) && (e._firestoreClient._uninitializedComponentsProvider = {\n        _offlineKind: i.localCache.kind,\n        _offline: i.localCache._offlineComponentProvider,\n        _online: i.localCache._onlineComponentProvider\n    });\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * Must be called before any other functions (other than\n * {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * If this fails, `enableIndexedDbPersistence()` will reject the promise it\n * returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n *   * failed-precondition: The app is already open in another browser tab.\n *   * unimplemented: The browser is incompatible with the offline\n *     persistence implementation.\n *\n * Persistence cannot be used in a Node.js environment.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */ function enableIndexedDbPersistence(e, t) {\n    __PRIVATE_verifyNotInitialized(e = __PRIVATE_cast(e, Firestore));\n    const n = ensureFirestoreConfigured(e);\n    if (n._uninitializedComponentsProvider) throw new FirestoreError(v.FAILED_PRECONDITION, \"SDK cache is already specified.\");\n    __PRIVATE_logWarn(\"enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.\");\n    const r = e._freezeSettings(), i = new OnlineComponentProvider;\n    return __PRIVATE_setPersistenceProviders(n, i, new __PRIVATE_IndexedDbOfflineComponentProvider(i, r.cacheSizeBytes, null == t ? void 0 : t.forceOwnership));\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise\n * it returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n *   * failed-precondition: The app is already open in another browser tab and\n *     multi-tab is not enabled.\n *   * unimplemented: The browser is incompatible with the offline\n *     persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */ function enableMultiTabIndexedDbPersistence(e) {\n    __PRIVATE_verifyNotInitialized(e = __PRIVATE_cast(e, Firestore));\n    const t = ensureFirestoreConfigured(e);\n    if (t._uninitializedComponentsProvider) throw new FirestoreError(v.FAILED_PRECONDITION, \"SDK cache is already specified.\");\n    __PRIVATE_logWarn(\"enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.\");\n    const n = e._freezeSettings(), r = new OnlineComponentProvider;\n    return __PRIVATE_setPersistenceProviders(t, r, new __PRIVATE_MultiTabOfflineComponentProvider(r, n.cacheSizeBytes));\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */ function __PRIVATE_setPersistenceProviders(e, t, n) {\n    const r = new __PRIVATE_Deferred;\n    return e.asyncQueue.enqueue((async () => {\n        try {\n            await __PRIVATE_setOfflineComponentProvider(e, n), await __PRIVATE_setOnlineComponentProvider(e, t), \n            r.resolve();\n        } catch (e) {\n            const t = e;\n            if (!__PRIVATE_canFallbackFromIndexedDbError(t)) throw t;\n            __PRIVATE_logWarn(\"Error enabling indexeddb cache. Falling back to memory cache: \" + t), \n            r.reject(t);\n        }\n    })).then((() => r.promise));\n}\n\n/**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */ function clearIndexedDbPersistence(e) {\n    if (e._initialized && !e._terminated) throw new FirestoreError(v.FAILED_PRECONDITION, \"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.\");\n    const t = new __PRIVATE_Deferred;\n    return e._queue.enqueueAndForgetEvenWhileRestricted((async () => {\n        try {\n            await async function __PRIVATE_indexedDbClearPersistence(e) {\n                if (!__PRIVATE_SimpleDb.v()) return Promise.resolve();\n                const t = e + \"main\";\n                await __PRIVATE_SimpleDb.delete(t);\n            }(__PRIVATE_indexedDbStoragePrefix(e._databaseId, e._persistenceKey)), t.resolve();\n        } catch (e) {\n            t.reject(e);\n        }\n    })), t.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */ function waitForPendingWrites(e) {\n    return function __PRIVATE_firestoreClientWaitForPendingWrites(e) {\n        const t = new __PRIVATE_Deferred;\n        return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineRegisterPendingWritesCallback(await __PRIVATE_getSyncEngine(e), t))), \n        t.promise;\n    }(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */ function enableNetwork(e) {\n    return __PRIVATE_firestoreClientEnableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */ function disableNetwork(e) {\n    return __PRIVATE_firestoreClientDisableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */ function terminate(e) {\n    return _removeServiceInstance(e.app, \"firestore\", e._databaseId.database), e._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise<LoadBundleTaskProgress>`.\n */ function loadBundle(e, t) {\n    const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), r = new LoadBundleTask;\n    return __PRIVATE_firestoreClientLoadBundle(n, e._databaseId, t, r), r;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged  into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */ function namedQuery(e, t) {\n    return __PRIVATE_firestoreClientGetNamedQuery(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), t).then((t => t ? new Query(e, null, t.query) : null));\n}\n\nfunction __PRIVATE_verifyNotInitialized(e) {\n    if (e._initialized || e._terminated) throw new FirestoreError(v.FAILED_PRECONDITION, \"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nclass AggregateField {\n    /**\n     * Create a new AggregateField<T>\n     * @param _aggregateType Specifies the type of aggregation operation to perform.\n     * @param _internalFieldPath Optionally specifies the field that is aggregated.\n     * @internal\n     */\n    constructor(\n    // TODO (sum/avg) make aggregateType public when the feature is supported\n    e = \"count\", t) {\n        this._aggregateType = e, this._internalFieldPath = t, \n        /** A type string to uniquely identify instances of this class. */\n        this.type = \"AggregateField\";\n    }\n}\n\n/**\n * The results of executing an aggregation query.\n */ class AggregateQuerySnapshot {\n    /** @hideconstructor */\n    constructor(e, t, n) {\n        this._userDataWriter = t, this._data = n, \n        /** A type string to uniquely identify instances of this class. */\n        this.type = \"AggregateQuerySnapshot\", this.query = e;\n    }\n    /**\n     * Returns the results of the aggregations performed over the underlying\n     * query.\n     *\n     * The keys of the returned object will be the same as those of the\n     * `AggregateSpec` object specified to the aggregation method, and the values\n     * will be the corresponding aggregation result.\n     *\n     * @returns The results of the aggregations performed over the underlying\n     * query.\n     */    data() {\n        return this._userDataWriter.convertObjectMap(this._data);\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing an array of bytes.\n */ class Bytes {\n    /** @hideconstructor */\n    constructor(e) {\n        this._byteString = e;\n    }\n    /**\n     * Creates a new `Bytes` object from the given Base64 string, converting it to\n     * bytes.\n     *\n     * @param base64 - The Base64 string used to create the `Bytes` object.\n     */    static fromBase64String(e) {\n        try {\n            return new Bytes(ByteString.fromBase64String(e));\n        } catch (e) {\n            throw new FirestoreError(v.INVALID_ARGUMENT, \"Failed to construct data from Base64 string: \" + e);\n        }\n    }\n    /**\n     * Creates a new `Bytes` object from the given Uint8Array.\n     *\n     * @param array - The Uint8Array used to create the `Bytes` object.\n     */    static fromUint8Array(e) {\n        return new Bytes(ByteString.fromUint8Array(e));\n    }\n    /**\n     * Returns the underlying bytes as a Base64-encoded string.\n     *\n     * @returns The Base64-encoded string created from the `Bytes` object.\n     */    toBase64() {\n        return this._byteString.toBase64();\n    }\n    /**\n     * Returns the underlying bytes in a new `Uint8Array`.\n     *\n     * @returns The Uint8Array created from the `Bytes` object.\n     */    toUint8Array() {\n        return this._byteString.toUint8Array();\n    }\n    /**\n     * Returns a string representation of the `Bytes` object.\n     *\n     * @returns A string representation of the `Bytes` object.\n     */    toString() {\n        return \"Bytes(base64: \" + this.toBase64() + \")\";\n    }\n    /**\n     * Returns true if this `Bytes` object is equal to the provided one.\n     *\n     * @param other - The `Bytes` object to compare against.\n     * @returns true if this `Bytes` object is equal to the provided one.\n     */    isEqual(e) {\n        return this._byteString.isEqual(e._byteString);\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */ class FieldPath {\n    /**\n     * Creates a `FieldPath` from the provided field names. If more than one field\n     * name is provided, the path will point to a nested field in a document.\n     *\n     * @param fieldNames - A list of field names.\n     */\n    constructor(...e) {\n        for (let t = 0; t < e.length; ++t) if (0 === e[t].length) throw new FirestoreError(v.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). Field names must not be empty.\");\n        this._internalPath = new FieldPath$1(e);\n    }\n    /**\n     * Returns true if this `FieldPath` is equal to the provided one.\n     *\n     * @param other - The `FieldPath` to compare against.\n     * @returns true if this `FieldPath` is equal to the provided one.\n     */    isEqual(e) {\n        return this._internalPath.isEqual(e._internalPath);\n    }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */ function documentId() {\n    return new FieldPath(\"__name__\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */ class FieldValue {\n    /**\n     * @param _methodName - The public API endpoint that returns this class.\n     * @hideconstructor\n     */\n    constructor(e) {\n        this._methodName = e;\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */ class GeoPoint {\n    /**\n     * Creates a new immutable `GeoPoint` object with the provided latitude and\n     * longitude values.\n     * @param latitude - The latitude as number between -90 and 90.\n     * @param longitude - The longitude as number between -180 and 180.\n     */\n    constructor(e, t) {\n        if (!isFinite(e) || e < -90 || e > 90) throw new FirestoreError(v.INVALID_ARGUMENT, \"Latitude must be a number between -90 and 90, but was: \" + e);\n        if (!isFinite(t) || t < -180 || t > 180) throw new FirestoreError(v.INVALID_ARGUMENT, \"Longitude must be a number between -180 and 180, but was: \" + t);\n        this._lat = e, this._long = t;\n    }\n    /**\n     * The latitude of this `GeoPoint` instance.\n     */    get latitude() {\n        return this._lat;\n    }\n    /**\n     * The longitude of this `GeoPoint` instance.\n     */    get longitude() {\n        return this._long;\n    }\n    /**\n     * Returns true if this `GeoPoint` is equal to the provided one.\n     *\n     * @param other - The `GeoPoint` to compare against.\n     * @returns true if this `GeoPoint` is equal to the provided one.\n     */    isEqual(e) {\n        return this._lat === e._lat && this._long === e._long;\n    }\n    /** Returns a JSON-serializable representation of this GeoPoint. */    toJSON() {\n        return {\n            latitude: this._lat,\n            longitude: this._long\n        };\n    }\n    /**\n     * Actually private to JS consumers of our API, so this function is prefixed\n     * with an underscore.\n     */    _compareTo(e) {\n        return __PRIVATE_primitiveComparator(this._lat, e._lat) || __PRIVATE_primitiveComparator(this._long, e._long);\n    }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const pe = /^__.*__$/;\n\n/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData {\n    constructor(e, t, n) {\n        this.data = e, this.fieldMask = t, this.fieldTransforms = n;\n    }\n    toMutation(e, t) {\n        return null !== this.fieldMask ? new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms) : new __PRIVATE_SetMutation(e, this.data, t, this.fieldTransforms);\n    }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */ class ParsedUpdateData {\n    constructor(e, \n    // The fieldMask does not include document transforms.\n    t, n) {\n        this.data = e, this.fieldMask = t, this.fieldTransforms = n;\n    }\n    toMutation(e, t) {\n        return new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms);\n    }\n}\n\nfunction __PRIVATE_isWrite(e) {\n    switch (e) {\n      case 0 /* UserDataSource.Set */ :\n // fall through\n              case 2 /* UserDataSource.MergeSet */ :\n // fall through\n              case 1 /* UserDataSource.Update */ :\n        return !0;\n\n      case 3 /* UserDataSource.Argument */ :\n      case 4 /* UserDataSource.ArrayArgument */ :\n        return !1;\n\n      default:\n        throw fail();\n    }\n}\n\n/** A \"context\" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl {\n    /**\n     * Initializes a ParseContext with the given source and path.\n     *\n     * @param settings - The settings for the parser.\n     * @param databaseId - The database ID of the Firestore instance.\n     * @param serializer - The serializer to use to generate the Value proto.\n     * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n     * rather than throw.\n     * @param fieldTransforms - A mutable list of field transforms encountered\n     * while parsing the data.\n     * @param fieldMask - A mutable list of field paths encountered while parsing\n     * the data.\n     *\n     * TODO(b/34871131): We don't support array paths right now, so path can be\n     * null to indicate the context represents any location within an array (in\n     * which case certain features will not work and errors will be somewhat\n     * compromised).\n     */\n    constructor(e, t, n, r, i, s) {\n        this.settings = e, this.databaseId = t, this.serializer = n, this.ignoreUndefinedProperties = r, \n        // Minor hack: If fieldTransforms is undefined, we assume this is an\n        // external call and we need to validate the entire path.\n        void 0 === i && this.au(), this.fieldTransforms = i || [], this.fieldMask = s || [];\n    }\n    get path() {\n        return this.settings.path;\n    }\n    get uu() {\n        return this.settings.uu;\n    }\n    /** Returns a new context with the specified settings overwritten. */    cu(e) {\n        return new __PRIVATE_ParseContextImpl(Object.assign(Object.assign({}, this.settings), e), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);\n    }\n    lu(e) {\n        var t;\n        const n = null === (t = this.path) || void 0 === t ? void 0 : t.child(e), r = this.cu({\n            path: n,\n            hu: !1\n        });\n        return r.Pu(e), r;\n    }\n    Iu(e) {\n        var t;\n        const n = null === (t = this.path) || void 0 === t ? void 0 : t.child(e), r = this.cu({\n            path: n,\n            hu: !1\n        });\n        return r.au(), r;\n    }\n    Tu(e) {\n        // TODO(b/34871131): We don't support array paths right now; so make path\n        // undefined.\n        return this.cu({\n            path: void 0,\n            hu: !0\n        });\n    }\n    Eu(e) {\n        return __PRIVATE_createError(e, this.settings.methodName, this.settings.du || !1, this.path, this.settings.Au);\n    }\n    /** Returns 'true' if 'fieldPath' was traversed when creating this context. */    contains(e) {\n        return void 0 !== this.fieldMask.find((t => e.isPrefixOf(t))) || void 0 !== this.fieldTransforms.find((t => e.isPrefixOf(t.field)));\n    }\n    au() {\n        // TODO(b/34871131): Remove null check once we have proper paths for fields\n        // within arrays.\n        if (this.path) for (let e = 0; e < this.path.length; e++) this.Pu(this.path.get(e));\n    }\n    Pu(e) {\n        if (0 === e.length) throw this.Eu(\"Document fields must not be empty\");\n        if (__PRIVATE_isWrite(this.uu) && pe.test(e)) throw this.Eu('Document fields cannot begin and end with \"__\"');\n    }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */ class __PRIVATE_UserDataReader {\n    constructor(e, t, n) {\n        this.databaseId = e, this.ignoreUndefinedProperties = t, this.serializer = n || __PRIVATE_newSerializer(e);\n    }\n    /** Creates a new top-level parse context. */    Ru(e, t, n, r = !1) {\n        return new __PRIVATE_ParseContextImpl({\n            uu: e,\n            methodName: t,\n            Au: n,\n            path: FieldPath$1.emptyPath(),\n            hu: !1,\n            du: r\n        }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);\n    }\n}\n\nfunction __PRIVATE_newUserDataReader(e) {\n    const t = e._freezeSettings(), n = __PRIVATE_newSerializer(e._databaseId);\n    return new __PRIVATE_UserDataReader(e._databaseId, !!t.ignoreUndefinedProperties, n);\n}\n\n/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(e, t, n, r, i, s = {}) {\n    const o = e.Ru(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , t, n, i);\n    __PRIVATE_validatePlainObject(\"Data must be an object, but it was:\", o, r);\n    const _ = __PRIVATE_parseObject(r, o);\n    let a, u;\n    if (s.merge) a = new FieldMask(o.fieldMask), u = o.fieldTransforms; else if (s.mergeFields) {\n        const e = [];\n        for (const r of s.mergeFields) {\n            const i = __PRIVATE_fieldPathFromArgument$1(t, r, n);\n            if (!o.contains(i)) throw new FirestoreError(v.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);\n            __PRIVATE_fieldMaskContains(e, i) || e.push(i);\n        }\n        a = new FieldMask(e), u = o.fieldTransforms.filter((e => a.covers(e.field)));\n    } else a = null, u = o.fieldTransforms;\n    return new ParsedSetData(new ObjectValue(_), a, u);\n}\n\nclass __PRIVATE_DeleteFieldValueImpl extends FieldValue {\n    _toFieldTransform(e) {\n        if (2 /* UserDataSource.MergeSet */ !== e.uu) throw 1 /* UserDataSource.Update */ === e.uu ? e.Eu(`${this._methodName}() can only appear at the top level of your update data`) : e.Eu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);\n        // No transform to add for a delete, but we need to add it to our\n        // fieldMask so it gets deleted.\n        return e.fieldMask.push(e.path), null;\n    }\n    isEqual(e) {\n        return e instanceof __PRIVATE_DeleteFieldValueImpl;\n    }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n *     context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */ function __PRIVATE_createSentinelChildContext(e, t, n) {\n    return new __PRIVATE_ParseContextImpl({\n        uu: 3 /* UserDataSource.Argument */ ,\n        Au: t.settings.Au,\n        methodName: e._methodName,\n        hu: n\n    }, t.databaseId, t.serializer, t.ignoreUndefinedProperties);\n}\n\nclass __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue {\n    _toFieldTransform(e) {\n        return new FieldTransform(e.path, new __PRIVATE_ServerTimestampTransform);\n    }\n    isEqual(e) {\n        return e instanceof __PRIVATE_ServerTimestampFieldValueImpl;\n    }\n}\n\nclass __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue {\n    constructor(e, t) {\n        super(e), this.Vu = t;\n    }\n    _toFieldTransform(e) {\n        const t = __PRIVATE_createSentinelChildContext(this, e, \n        /*array=*/ !0), n = this.Vu.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayUnionTransformOperation(n);\n        return new FieldTransform(e.path, r);\n    }\n    isEqual(e) {\n        // TODO(mrschmidt): Implement isEquals\n        return this === e;\n    }\n}\n\nclass __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue {\n    constructor(e, t) {\n        super(e), this.Vu = t;\n    }\n    _toFieldTransform(e) {\n        const t = __PRIVATE_createSentinelChildContext(this, e, \n        /*array=*/ !0), n = this.Vu.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayRemoveTransformOperation(n);\n        return new FieldTransform(e.path, r);\n    }\n    isEqual(e) {\n        // TODO(mrschmidt): Implement isEquals\n        return this === e;\n    }\n}\n\nclass __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue {\n    constructor(e, t) {\n        super(e), this.mu = t;\n    }\n    _toFieldTransform(e) {\n        const t = new __PRIVATE_NumericIncrementTransformOperation(e.serializer, toNumber(e.serializer, this.mu));\n        return new FieldTransform(e.path, t);\n    }\n    isEqual(e) {\n        // TODO(mrschmidt): Implement isEquals\n        return this === e;\n    }\n}\n\n/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(e, t, n, r) {\n    const i = e.Ru(1 /* UserDataSource.Update */ , t, n);\n    __PRIVATE_validatePlainObject(\"Data must be an object, but it was:\", i, r);\n    const s = [], o = ObjectValue.empty();\n    forEach(r, ((e, r) => {\n        const _ = __PRIVATE_fieldPathFromDotSeparatedString(t, e, n);\n        // For Compat types, we have to \"extract\" the underlying types before\n        // performing validation.\n                r = getModularInstance(r);\n        const a = i.Iu(_);\n        if (r instanceof __PRIVATE_DeleteFieldValueImpl) \n        // Add it to the field mask, but don't add anything to updateData.\n        s.push(_); else {\n            const e = __PRIVATE_parseData(r, a);\n            null != e && (s.push(_), o.set(_, e));\n        }\n    }));\n    const _ = new FieldMask(s);\n    return new ParsedUpdateData(o, _, i.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(e, t, n, r, i, s) {\n    const o = e.Ru(1 /* UserDataSource.Update */ , t, n), _ = [ __PRIVATE_fieldPathFromArgument$1(t, r, n) ], a = [ i ];\n    if (s.length % 2 != 0) throw new FirestoreError(v.INVALID_ARGUMENT, `Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);\n    for (let e = 0; e < s.length; e += 2) _.push(__PRIVATE_fieldPathFromArgument$1(t, s[e])), \n    a.push(s[e + 1]);\n    const u = [], c = ObjectValue.empty();\n    // We iterate in reverse order to pick the last value for a field if the\n    // user specified the field multiple times.\n    for (let e = _.length - 1; e >= 0; --e) if (!__PRIVATE_fieldMaskContains(u, _[e])) {\n        const t = _[e];\n        let n = a[e];\n        // For Compat types, we have to \"extract\" the underlying types before\n        // performing validation.\n                n = getModularInstance(n);\n        const r = o.Iu(t);\n        if (n instanceof __PRIVATE_DeleteFieldValueImpl) \n        // Add it to the field mask, but don't add anything to updateData.\n        u.push(t); else {\n            const e = __PRIVATE_parseData(n, r);\n            null != e && (u.push(t), c.set(t, e));\n        }\n    }\n    const l = new FieldMask(u);\n    return new ParsedUpdateData(c, l, o.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */ function __PRIVATE_parseQueryValue(e, t, n, r = !1) {\n    return __PRIVATE_parseData(n, e.Ru(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , t));\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */ function __PRIVATE_parseData(e, t) {\n    if (__PRIVATE_looksLikeJsonObject(\n    // Unwrap the API type from the Compat SDK. This will return the API type\n    // from firestore-exp.\n    e = getModularInstance(e))) return __PRIVATE_validatePlainObject(\"Unsupported field value:\", t, e), \n    __PRIVATE_parseObject(e, t);\n    if (e instanceof FieldValue) \n    // FieldValues usually parse into transforms (except deleteField())\n    // in which case we do not want to include this field in our parsed data\n    // (as doing so will overwrite the field directly prior to the transform\n    // trying to transform it). So we don't add this location to\n    // context.fieldMask and we return null as our parsing result.\n    /**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\n    return function __PRIVATE_parseSentinelFieldValue(e, t) {\n        // Sentinels are only supported with writes, and not within arrays.\n        if (!__PRIVATE_isWrite(t.uu)) throw t.Eu(`${e._methodName}() can only be used with update() and set()`);\n        if (!t.path) throw t.Eu(`${e._methodName}() is not currently supported inside arrays`);\n        const n = e._toFieldTransform(t);\n        n && t.fieldTransforms.push(n);\n    }\n    /**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */ (e, t), null;\n    if (void 0 === e && t.ignoreUndefinedProperties) \n    // If the input is undefined it can never participate in the fieldMask, so\n    // don't handle this below. If `ignoreUndefinedProperties` is false,\n    // `parseScalarValue` will reject an undefined value.\n    return null;\n    if (\n    // If context.path is null we are inside an array and we don't support\n    // field mask paths more granular than the top-level array.\n    t.path && t.fieldMask.push(t.path), e instanceof Array) {\n        // TODO(b/34871131): Include the path containing the array in the error\n        // message.\n        // In the case of IN queries, the parsed data is an array (representing\n        // the set of values to be included for the IN query) that may directly\n        // contain additional arrays (each representing an individual field\n        // value), so we disable this validation.\n        if (t.settings.hu && 4 /* UserDataSource.ArrayArgument */ !== t.uu) throw t.Eu(\"Nested arrays are not supported\");\n        return function __PRIVATE_parseArray(e, t) {\n            const n = [];\n            let r = 0;\n            for (const i of e) {\n                let e = __PRIVATE_parseData(i, t.Tu(r));\n                null == e && (\n                // Just include nulls in the array for fields being replaced with a\n                // sentinel.\n                e = {\n                    nullValue: \"NULL_VALUE\"\n                }), n.push(e), r++;\n            }\n            return {\n                arrayValue: {\n                    values: n\n                }\n            };\n        }(e, t);\n    }\n    return function __PRIVATE_parseScalarValue(e, t) {\n        if (null === (e = getModularInstance(e))) return {\n            nullValue: \"NULL_VALUE\"\n        };\n        if (\"number\" == typeof e) return toNumber(t.serializer, e);\n        if (\"boolean\" == typeof e) return {\n            booleanValue: e\n        };\n        if (\"string\" == typeof e) return {\n            stringValue: e\n        };\n        if (e instanceof Date) {\n            const n = Timestamp.fromDate(e);\n            return {\n                timestampValue: toTimestamp(t.serializer, n)\n            };\n        }\n        if (e instanceof Timestamp) {\n            // Firestore backend truncates precision down to microseconds. To ensure\n            // offline mode works the same with regards to truncation, perform the\n            // truncation immediately without waiting for the backend to do that.\n            const n = new Timestamp(e.seconds, 1e3 * Math.floor(e.nanoseconds / 1e3));\n            return {\n                timestampValue: toTimestamp(t.serializer, n)\n            };\n        }\n        if (e instanceof GeoPoint) return {\n            geoPointValue: {\n                latitude: e.latitude,\n                longitude: e.longitude\n            }\n        };\n        if (e instanceof Bytes) return {\n            bytesValue: __PRIVATE_toBytes(t.serializer, e._byteString)\n        };\n        if (e instanceof DocumentReference) {\n            const n = t.databaseId, r = e.firestore._databaseId;\n            if (!r.isEqual(n)) throw t.Eu(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);\n            return {\n                referenceValue: __PRIVATE_toResourceName(e.firestore._databaseId || t.databaseId, e._key.path)\n            };\n        }\n        throw t.Eu(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`);\n    }\n    /**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */ (e, t);\n}\n\nfunction __PRIVATE_parseObject(e, t) {\n    const n = {};\n    return isEmpty(e) ? \n    // If we encounter an empty object, we explicitly add it to the update\n    // mask to ensure that the server creates a map entry.\n    t.path && t.path.length > 0 && t.fieldMask.push(t.path) : forEach(e, ((e, r) => {\n        const i = __PRIVATE_parseData(r, t.lu(e));\n        null != i && (n[e] = i);\n    })), {\n        mapValue: {\n            fields: n\n        }\n    };\n}\n\nfunction __PRIVATE_looksLikeJsonObject(e) {\n    return !(\"object\" != typeof e || null === e || e instanceof Array || e instanceof Date || e instanceof Timestamp || e instanceof GeoPoint || e instanceof Bytes || e instanceof DocumentReference || e instanceof FieldValue);\n}\n\nfunction __PRIVATE_validatePlainObject(e, t, n) {\n    if (!__PRIVATE_looksLikeJsonObject(n) || !function __PRIVATE_isPlainObject(e) {\n        return \"object\" == typeof e && null !== e && (Object.getPrototypeOf(e) === Object.prototype || null === Object.getPrototypeOf(e));\n    }(n)) {\n        const r = __PRIVATE_valueDescription(n);\n        throw \"an object\" === r ? t.Eu(e + \" a custom object\") : t.Eu(e + \" \" + r);\n    }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */ function __PRIVATE_fieldPathFromArgument$1(e, t, n) {\n    if ((\n    // If required, replace the FieldPath Compat class with with the firestore-exp\n    // FieldPath.\n    t = getModularInstance(t)) instanceof FieldPath) return t._internalPath;\n    if (\"string\" == typeof t) return __PRIVATE_fieldPathFromDotSeparatedString(e, t);\n    throw __PRIVATE_createError(\"Field path arguments must be of type string or \", e, \n    /* hasConverter= */ !1, \n    /* path= */ void 0, n);\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */ const ye = new RegExp(\"[~\\\\*/\\\\[\\\\]]\");\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */ function __PRIVATE_fieldPathFromDotSeparatedString(e, t, n) {\n    if (t.search(ye) >= 0) throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`, e, \n    /* hasConverter= */ !1, \n    /* path= */ void 0, n);\n    try {\n        return new FieldPath(...t.split(\".\"))._internalPath;\n    } catch (r) {\n        throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, e, \n        /* hasConverter= */ !1, \n        /* path= */ void 0, n);\n    }\n}\n\nfunction __PRIVATE_createError(e, t, n, r, i) {\n    const s = r && !r.isEmpty(), o = void 0 !== i;\n    let _ = `Function ${t}() called with invalid data`;\n    n && (_ += \" (via `toFirestore()`)\"), _ += \". \";\n    let a = \"\";\n    return (s || o) && (a += \" (found\", s && (a += ` in field ${r}`), o && (a += ` in document ${i}`), \n    a += \")\"), new FirestoreError(v.INVALID_ARGUMENT, _ + e + a);\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(e, t) {\n    return e.some((e => e.isEqual(t)));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class DocumentSnapshot$1 {\n    // Note: This class is stripped down version of the DocumentSnapshot in\n    // the legacy SDK. The changes are:\n    // - No support for SnapshotMetadata.\n    // - No support for SnapshotOptions.\n    /** @hideconstructor protected */\n    constructor(e, t, n, r, i) {\n        this._firestore = e, this._userDataWriter = t, this._key = n, this._document = r, \n        this._converter = i;\n    }\n    /** Property of the `DocumentSnapshot` that provides the document's ID. */    get id() {\n        return this._key.path.lastSegment();\n    }\n    /**\n     * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n     */    get ref() {\n        return new DocumentReference(this._firestore, this._converter, this._key);\n    }\n    /**\n     * Signals whether or not the document at the snapshot's location exists.\n     *\n     * @returns true if the document exists.\n     */    exists() {\n        return null !== this._document;\n    }\n    /**\n     * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n     * the document doesn't exist.\n     *\n     * @returns An `Object` containing all fields in the document or `undefined`\n     * if the document doesn't exist.\n     */    data() {\n        if (this._document) {\n            if (this._converter) {\n                // We only want to use the converter and create a new DocumentSnapshot\n                // if a converter has been provided.\n                const e = new QueryDocumentSnapshot$1(this._firestore, this._userDataWriter, this._key, this._document, \n                /* converter= */ null);\n                return this._converter.fromFirestore(e);\n            }\n            return this._userDataWriter.convertValue(this._document.data.value);\n        }\n    }\n    /**\n     * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n     * document or field doesn't exist.\n     *\n     * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n     * field.\n     * @returns The data at the specified field location or undefined if no such\n     * field exists in the document.\n     */\n    // We are using `any` here to avoid an explicit cast by our users.\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    get(e) {\n        if (this._document) {\n            const t = this._document.data.field(__PRIVATE_fieldPathFromArgument(\"DocumentSnapshot.get\", e));\n            if (null !== t) return this._userDataWriter.convertValue(t);\n        }\n    }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 {\n    /**\n     * Retrieves all fields in the document as an `Object`.\n     *\n     * @override\n     * @returns An `Object` containing all fields in the document.\n     */\n    data() {\n        return super.data();\n    }\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */ function __PRIVATE_fieldPathFromArgument(e, t) {\n    return \"string\" == typeof t ? __PRIVATE_fieldPathFromDotSeparatedString(e, t) : t instanceof FieldPath ? t._internalPath : t._delegate._internalPath;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e) {\n    if (\"L\" /* LimitType.Last */ === e.limitType && 0 === e.explicitOrderBy.length) throw new FirestoreError(v.UNIMPLEMENTED, \"limitToLast() queries require specifying at least one orderBy() clause\");\n}\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */ class AppliableConstraint {}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */ class QueryConstraint extends AppliableConstraint {}\n\nfunction query(e, t, ...n) {\n    let r = [];\n    t instanceof AppliableConstraint && r.push(t), r = r.concat(n), function __PRIVATE_validateQueryConstraintArray(e) {\n        const t = e.filter((e => e instanceof QueryCompositeFilterConstraint)).length, n = e.filter((e => e instanceof QueryFieldFilterConstraint)).length;\n        if (t > 1 || t > 0 && n > 0) throw new FirestoreError(v.INVALID_ARGUMENT, \"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.\");\n    }\n    /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n    /**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */ (r);\n    for (const t of r) e = t._apply(e);\n    return e;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */ class QueryFieldFilterConstraint extends QueryConstraint {\n    /**\n     * @internal\n     */\n    constructor(e, t, n) {\n        super(), this._field = e, this._op = t, this._value = n, \n        /** The type of this query constraint */\n        this.type = \"where\";\n    }\n    static _create(e, t, n) {\n        return new QueryFieldFilterConstraint(e, t, n);\n    }\n    _apply(e) {\n        const t = this._parse(e);\n        return __PRIVATE_validateNewFieldFilter(e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t));\n    }\n    _parse(e) {\n        const t = __PRIVATE_newUserDataReader(e.firestore), n = function __PRIVATE_newQueryFilter(e, t, n, r, i, s, o) {\n            let _;\n            if (i.isKeyField()) {\n                if (\"array-contains\" /* Operator.ARRAY_CONTAINS */ === s || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid Query. You can't perform '${s}' queries on documentId().`);\n                if (\"in\" /* Operator.IN */ === s || \"not-in\" /* Operator.NOT_IN */ === s) {\n                    __PRIVATE_validateDisjunctiveFilterElements(o, s);\n                    const t = [];\n                    for (const n of o) t.push(__PRIVATE_parseDocumentIdValue(r, e, n));\n                    _ = {\n                        arrayValue: {\n                            values: t\n                        }\n                    };\n                } else _ = __PRIVATE_parseDocumentIdValue(r, e, o);\n            } else \"in\" /* Operator.IN */ !== s && \"not-in\" /* Operator.NOT_IN */ !== s && \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), \n            _ = __PRIVATE_parseQueryValue(n, t, o, \n            /* allowArrays= */ \"in\" /* Operator.IN */ === s || \"not-in\" /* Operator.NOT_IN */ === s);\n            return FieldFilter.create(i, s, _);\n        }(e._query, \"where\", t, e.firestore._databaseId, this._field, this._op, this._value);\n        return n;\n    }\n}\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"&lt;\", \"&lt;=\", \"==\", \"&lt;\",\n *   \"&lt;=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */ function where(e, t, n) {\n    const r = t, i = __PRIVATE_fieldPathFromArgument(\"where\", e);\n    return QueryFieldFilterConstraint._create(i, r, n);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */ class QueryCompositeFilterConstraint extends AppliableConstraint {\n    /**\n     * @internal\n     */\n    constructor(\n    /** The type of this query constraint */\n    e, t) {\n        super(), this.type = e, this._queryConstraints = t;\n    }\n    static _create(e, t) {\n        return new QueryCompositeFilterConstraint(e, t);\n    }\n    _parse(e) {\n        const t = this._queryConstraints.map((t => t._parse(e))).filter((e => e.getFilters().length > 0));\n        return 1 === t.length ? t[0] : CompositeFilter.create(t, this._getOperator());\n    }\n    _apply(e) {\n        const t = this._parse(e);\n        return 0 === t.getFilters().length ? e : (function __PRIVATE_validateNewFilter(e, t) {\n            let n = e;\n            const r = t.getFlattenedFilters();\n            for (const e of r) __PRIVATE_validateNewFieldFilter(n, e), n = __PRIVATE_queryWithAddedFilter(n, e);\n        }\n        // Checks if any of the provided filter operators are included in the given list of filters and\n        // returns the first one that is, or null if none are.\n        (e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t)));\n    }\n    _getQueryConstraints() {\n        return this._queryConstraints;\n    }\n    _getOperator() {\n        return \"and\" === this.type ? \"and\" /* CompositeOperator.AND */ : \"or\" /* CompositeOperator.OR */;\n    }\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */ function or(...e) {\n    // Only support QueryFilterConstraints\n    return e.forEach((e => __PRIVATE_validateQueryFilterConstraint(\"or\", e))), QueryCompositeFilterConstraint._create(\"or\" /* CompositeOperator.OR */ , e);\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */ function and(...e) {\n    // Only support QueryFilterConstraints\n    return e.forEach((e => __PRIVATE_validateQueryFilterConstraint(\"and\", e))), QueryCompositeFilterConstraint._create(\"and\" /* CompositeOperator.AND */ , e);\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */ class QueryOrderByConstraint extends QueryConstraint {\n    /**\n     * @internal\n     */\n    constructor(e, t) {\n        super(), this._field = e, this._direction = t, \n        /** The type of this query constraint */\n        this.type = \"orderBy\";\n    }\n    static _create(e, t) {\n        return new QueryOrderByConstraint(e, t);\n    }\n    _apply(e) {\n        const t = function __PRIVATE_newQueryOrderBy(e, t, n) {\n            if (null !== e.startAt) throw new FirestoreError(v.INVALID_ARGUMENT, \"Invalid query. You must not call startAt() or startAfter() before calling orderBy().\");\n            if (null !== e.endAt) throw new FirestoreError(v.INVALID_ARGUMENT, \"Invalid query. You must not call endAt() or endBefore() before calling orderBy().\");\n            const r = new OrderBy(t, n);\n            return function __PRIVATE_validateNewOrderBy(e, t) {\n                if (null === __PRIVATE_getFirstOrderByField(e)) {\n                    // This is the first order by. It must match any inequality.\n                    const n = __PRIVATE_getInequalityFilterField(e);\n                    null !== n && __PRIVATE_validateOrderByAndInequalityMatch(e, n, t.field);\n                }\n            }(e, r), r;\n        }\n        /**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */ (e._query, this._field, this._direction);\n        return new Query(e.firestore, e.converter, function __PRIVATE_queryWithAddedOrderBy(e, t) {\n            // TODO(dimond): validate that orderBy does not list the same key twice.\n            const n = e.explicitOrderBy.concat([ t ]);\n            return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, n, e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt);\n        }(e._query, t));\n    }\n}\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */ function orderBy(e, t = \"asc\") {\n    const n = t, r = __PRIVATE_fieldPathFromArgument(\"orderBy\", e);\n    return QueryOrderByConstraint._create(r, n);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */ class QueryLimitConstraint extends QueryConstraint {\n    /**\n     * @internal\n     */\n    constructor(\n    /** The type of this query constraint */\n    e, t, n) {\n        super(), this.type = e, this._limit = t, this._limitType = n;\n    }\n    static _create(e, t, n) {\n        return new QueryLimitConstraint(e, t, n);\n    }\n    _apply(e) {\n        return new Query(e.firestore, e.converter, __PRIVATE_queryWithLimit(e._query, this._limit, this._limitType));\n    }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function limit(e) {\n    return __PRIVATE_validatePositiveNumber(\"limit\", e), QueryLimitConstraint._create(\"limit\", e, \"F\" /* LimitType.First */);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function limitToLast(e) {\n    return __PRIVATE_validatePositiveNumber(\"limitToLast\", e), QueryLimitConstraint._create(\"limitToLast\", e, \"L\" /* LimitType.Last */);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */ class QueryStartAtConstraint extends QueryConstraint {\n    /**\n     * @internal\n     */\n    constructor(\n    /** The type of this query constraint */\n    e, t, n) {\n        super(), this.type = e, this._docOrFields = t, this._inclusive = n;\n    }\n    static _create(e, t, n) {\n        return new QueryStartAtConstraint(e, t, n);\n    }\n    _apply(e) {\n        const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive);\n        return new Query(e.firestore, e.converter, function __PRIVATE_queryWithStartAt(e, t) {\n            return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, t, e.endAt);\n        }(e._query, t));\n    }\n}\n\nfunction startAt(...e) {\n    return QueryStartAtConstraint._create(\"startAt\", e, \n    /*inclusive=*/ !0);\n}\n\nfunction startAfter(...e) {\n    return QueryStartAtConstraint._create(\"startAfter\", e, \n    /*inclusive=*/ !1);\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */ class QueryEndAtConstraint extends QueryConstraint {\n    /**\n     * @internal\n     */\n    constructor(\n    /** The type of this query constraint */\n    e, t, n) {\n        super(), this.type = e, this._docOrFields = t, this._inclusive = n;\n    }\n    static _create(e, t, n) {\n        return new QueryEndAtConstraint(e, t, n);\n    }\n    _apply(e) {\n        const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive);\n        return new Query(e.firestore, e.converter, function __PRIVATE_queryWithEndAt(e, t) {\n            return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, t);\n        }(e._query, t));\n    }\n}\n\nfunction endBefore(...e) {\n    return QueryEndAtConstraint._create(\"endBefore\", e, \n    /*inclusive=*/ !1);\n}\n\nfunction endAt(...e) {\n    return QueryEndAtConstraint._create(\"endAt\", e, \n    /*inclusive=*/ !0);\n}\n\n/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(e, t, n, r) {\n    if (n[0] = getModularInstance(n[0]), n[0] instanceof DocumentSnapshot$1) return function __PRIVATE_newQueryBoundFromDocument(e, t, n, r, i) {\n        if (!r) throw new FirestoreError(v.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);\n        const s = [];\n        // Because people expect to continue/end a query at the exact document\n        // provided, we need to use the implicit sort order rather than the explicit\n        // sort order, because it's guaranteed to contain the document key. That way\n        // the position becomes unambiguous and the query continues/ends exactly at\n        // the provided document. Without the key (by using the explicit sort\n        // orders), multiple documents could match the position, yielding duplicate\n        // results.\n                for (const n of __PRIVATE_queryOrderBy(e)) if (n.field.isKeyField()) s.push(__PRIVATE_refValue(t, r.key)); else {\n            const e = r.data.field(n.field);\n            if (__PRIVATE_isServerTimestamp(e)) throw new FirestoreError(v.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field \"' + n.field + '\" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');\n            if (null === e) {\n                const e = n.field.canonicalString();\n                throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`);\n            }\n            s.push(e);\n        }\n        return new Bound(s, i);\n    }\n    /**\n * Converts a list of field values to a `Bound` for the given query.\n */ (e._query, e.firestore._databaseId, t, n[0]._document, r);\n    {\n        const i = __PRIVATE_newUserDataReader(e.firestore);\n        return function __PRIVATE_newQueryBoundFromFields(e, t, n, r, i, s) {\n            // Use explicit order by's because it has to match the query the user made\n            const o = e.explicitOrderBy;\n            if (i.length > o.length) throw new FirestoreError(v.INVALID_ARGUMENT, `Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);\n            const _ = [];\n            for (let s = 0; s < i.length; s++) {\n                const a = i[s];\n                if (o[s].field.isKeyField()) {\n                    if (\"string\" != typeof a) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof a}`);\n                    if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== a.indexOf(\"/\")) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${a}' contains a slash.`);\n                    const n = e.path.child(ResourcePath.fromString(a));\n                    if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);\n                    const i = new DocumentKey(n);\n                    _.push(__PRIVATE_refValue(t, i));\n                } else {\n                    const e = __PRIVATE_parseQueryValue(n, r, a);\n                    _.push(e);\n                }\n            }\n            return new Bound(_, s);\n        }\n        /**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */ (e._query, e.firestore._databaseId, i, t, n, r);\n    }\n}\n\nfunction __PRIVATE_parseDocumentIdValue(e, t, n) {\n    if (\"string\" == typeof (n = getModularInstance(n))) {\n        if (\"\" === n) throw new FirestoreError(v.INVALID_ARGUMENT, \"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.\");\n        if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== n.indexOf(\"/\")) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);\n        const r = t.path.child(ResourcePath.fromString(n));\n        if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);\n        return __PRIVATE_refValue(e, new DocumentKey(r));\n    }\n    if (n instanceof DocumentReference) return __PRIVATE_refValue(e, n._key);\n    throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(n)}.`);\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */ function __PRIVATE_validateDisjunctiveFilterElements(e, t) {\n    if (!Array.isArray(e) || 0 === e.length) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */ function __PRIVATE_validateNewFieldFilter(e, t) {\n    if (t.isInequality()) {\n        const n = __PRIVATE_getInequalityFilterField(e), r = t.field;\n        if (null !== n && !n.isEqual(r)) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${r.toString()}'`);\n        const i = __PRIVATE_getFirstOrderByField(e);\n        null !== i && __PRIVATE_validateOrderByAndInequalityMatch(e, r, i);\n    }\n    const n = function __PRIVATE_findOpInsideFilters(e, t) {\n        for (const n of e) for (const e of n.getFlattenedFilters()) if (t.indexOf(e.op) >= 0) return e.op;\n        return null;\n    }(e.filters, function __PRIVATE_conflictingOps(e) {\n        switch (e) {\n          case \"!=\" /* Operator.NOT_EQUAL */ :\n            return [ \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n          case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n          case \"in\" /* Operator.IN */ :\n            return [ \"not-in\" /* Operator.NOT_IN */ ];\n\n          case \"not-in\" /* Operator.NOT_IN */ :\n            return [ \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ , \"!=\" /* Operator.NOT_EQUAL */ ];\n\n          default:\n            return [];\n        }\n    }(t.op));\n    if (null !== n) \n    // Special case when it's a duplicate op to give a slightly clearer error message.\n    throw n === t.op ? new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${t.op.toString()}' filter.`) : new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`);\n}\n\nfunction __PRIVATE_validateOrderByAndInequalityMatch(e, t, n) {\n    if (!n.isEqual(t)) throw new FirestoreError(v.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);\n}\n\nfunction __PRIVATE_validateQueryFilterConstraint(e, t) {\n    if (!(t instanceof QueryFieldFilterConstraint || t instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(v.INVALID_ARGUMENT, `Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);\n}\n\nclass AbstractUserDataWriter {\n    convertValue(e, t = \"none\") {\n        switch (__PRIVATE_typeOrder(e)) {\n          case 0 /* TypeOrder.NullValue */ :\n            return null;\n\n          case 1 /* TypeOrder.BooleanValue */ :\n            return e.booleanValue;\n\n          case 2 /* TypeOrder.NumberValue */ :\n            return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);\n\n          case 3 /* TypeOrder.TimestampValue */ :\n            return this.convertTimestamp(e.timestampValue);\n\n          case 4 /* TypeOrder.ServerTimestampValue */ :\n            return this.convertServerTimestamp(e, t);\n\n          case 5 /* TypeOrder.StringValue */ :\n            return e.stringValue;\n\n          case 6 /* TypeOrder.BlobValue */ :\n            return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));\n\n          case 7 /* TypeOrder.RefValue */ :\n            return this.convertReference(e.referenceValue);\n\n          case 8 /* TypeOrder.GeoPointValue */ :\n            return this.convertGeoPoint(e.geoPointValue);\n\n          case 9 /* TypeOrder.ArrayValue */ :\n            return this.convertArray(e.arrayValue, t);\n\n          case 10 /* TypeOrder.ObjectValue */ :\n            return this.convertObject(e.mapValue, t);\n\n          default:\n            throw fail();\n        }\n    }\n    convertObject(e, t) {\n        return this.convertObjectMap(e.fields, t);\n    }\n    /**\n     * @internal\n     */    convertObjectMap(e, t = \"none\") {\n        const n = {};\n        return forEach(e, ((e, r) => {\n            n[e] = this.convertValue(r, t);\n        })), n;\n    }\n    convertGeoPoint(e) {\n        return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(e.longitude));\n    }\n    convertArray(e, t) {\n        return (e.values || []).map((e => this.convertValue(e, t)));\n    }\n    convertServerTimestamp(e, t) {\n        switch (t) {\n          case \"previous\":\n            const n = __PRIVATE_getPreviousValue(e);\n            return null == n ? null : this.convertValue(n, t);\n\n          case \"estimate\":\n            return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));\n\n          default:\n            return null;\n        }\n    }\n    convertTimestamp(e) {\n        const t = __PRIVATE_normalizeTimestamp(e);\n        return new Timestamp(t.seconds, t.nanos);\n    }\n    convertDocumentKey(e, t) {\n        const n = ResourcePath.fromString(e);\n        __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(n));\n        const r = new DatabaseId(n.get(1), n.get(3)), i = new DocumentKey(n.popFirst(5));\n        return r.isEqual(t) || \n        // TODO(b/64130202): Somehow support foreign references.\n        __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`), \n        i;\n    }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */ function __PRIVATE_applyFirestoreDataConverter(e, t, n) {\n    let r;\n    // Cast to `any` in order to satisfy the union type constraint on\n    // toFirestore().\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return r = e ? n && (n.merge || n.mergeFields) ? e.toFirestore(t, n) : e.toFirestore(t) : t, \n    r;\n}\n\nclass __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter {\n    constructor(e) {\n        super(), this.firestore = e;\n    }\n    convertBytes(e) {\n        return new Bytes(e);\n    }\n    convertReference(e) {\n        const t = this.convertDocumentKey(e, this.firestore._databaseId);\n        return new DocumentReference(this.firestore, /* converter= */ null, t);\n    }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n * @internal TODO (sum/avg) remove when public\n */ function sum(e) {\n    return new AggregateField(\"sum\", __PRIVATE_fieldPathFromArgument$1(\"sum\", e));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n * @internal TODO (sum/avg) remove when public\n */ function average(e) {\n    return new AggregateField(\"avg\", __PRIVATE_fieldPathFromArgument$1(\"average\", e));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n * @internal TODO (sum/avg) remove when public\n */ function count() {\n    return new AggregateField(\"count\");\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n * @internal TODO (sum/avg) remove when public\n */ function aggregateFieldEqual(e, t) {\n    var n, r;\n    return e instanceof AggregateField && t instanceof AggregateField && e._aggregateType === t._aggregateType && (null === (n = e._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (r = t._internalFieldPath) || void 0 === r ? void 0 : r.canonicalString());\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */ function aggregateQuerySnapshotEqual(e, t) {\n    return queryEqual(e.query, t.query) && deepEqual(e.data(), t.data());\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */ class SnapshotMetadata {\n    /** @hideconstructor */\n    constructor(e, t) {\n        this.hasPendingWrites = e, this.fromCache = t;\n    }\n    /**\n     * Returns true if this `SnapshotMetadata` is equal to the provided one.\n     *\n     * @param other - The `SnapshotMetadata` to compare against.\n     * @returns true if this `SnapshotMetadata` is equal to the provided one.\n     */    isEqual(e) {\n        return this.hasPendingWrites === e.hasPendingWrites && this.fromCache === e.fromCache;\n    }\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class DocumentSnapshot extends DocumentSnapshot$1 {\n    /** @hideconstructor protected */\n    constructor(e, t, n, r, i, s) {\n        super(e, t, n, r, s), this._firestore = e, this._firestoreImpl = e, this.metadata = i;\n    }\n    /**\n     * Returns whether or not the data exists. True if the document exists.\n     */    exists() {\n        return super.exists();\n    }\n    /**\n     * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n     * the document doesn't exist.\n     *\n     * By default, `serverTimestamp()` values that have not yet been\n     * set to their final value will be returned as `null`. You can override\n     * this by passing an options object.\n     *\n     * @param options - An options object to configure how data is retrieved from\n     * the snapshot (for example the desired behavior for server timestamps that\n     * have not yet been set to their final value).\n     * @returns An `Object` containing all fields in the document or `undefined` if\n     * the document doesn't exist.\n     */    data(e = {}) {\n        if (this._document) {\n            if (this._converter) {\n                // We only want to use the converter and create a new DocumentSnapshot\n                // if a converter has been provided.\n                const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, \n                /* converter= */ null);\n                return this._converter.fromFirestore(t, e);\n            }\n            return this._userDataWriter.convertValue(this._document.data.value, e.serverTimestamps);\n        }\n    }\n    /**\n     * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n     * document or field doesn't exist.\n     *\n     * By default, a `serverTimestamp()` that has not yet been set to\n     * its final value will be returned as `null`. You can override this by\n     * passing an options object.\n     *\n     * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n     * field.\n     * @param options - An options object to configure how the field is retrieved\n     * from the snapshot (for example the desired behavior for server timestamps\n     * that have not yet been set to their final value).\n     * @returns The data at the specified field location or undefined if no such\n     * field exists in the document.\n     */\n    // We are using `any` here to avoid an explicit cast by our users.\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    get(e, t = {}) {\n        if (this._document) {\n            const n = this._document.data.field(__PRIVATE_fieldPathFromArgument(\"DocumentSnapshot.get\", e));\n            if (null !== n) return this._userDataWriter.convertValue(n, t.serverTimestamps);\n        }\n    }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class QueryDocumentSnapshot extends DocumentSnapshot {\n    /**\n     * Retrieves all fields in the document as an `Object`.\n     *\n     * By default, `serverTimestamp()` values that have not yet been\n     * set to their final value will be returned as `null`. You can override\n     * this by passing an options object.\n     *\n     * @override\n     * @param options - An options object to configure how data is retrieved from\n     * the snapshot (for example the desired behavior for server timestamps that\n     * have not yet been set to their final value).\n     * @returns An `Object` containing all fields in the document.\n     */\n    data(e = {}) {\n        return super.data(e);\n    }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */ class QuerySnapshot {\n    /** @hideconstructor */\n    constructor(e, t, n, r) {\n        this._firestore = e, this._userDataWriter = t, this._snapshot = r, this.metadata = new SnapshotMetadata(r.hasPendingWrites, r.fromCache), \n        this.query = n;\n    }\n    /** An array of all the documents in the `QuerySnapshot`. */    get docs() {\n        const e = [];\n        return this.forEach((t => e.push(t))), e;\n    }\n    /** The number of documents in the `QuerySnapshot`. */    get size() {\n        return this._snapshot.docs.size;\n    }\n    /** True if there are no documents in the `QuerySnapshot`. */    get empty() {\n        return 0 === this.size;\n    }\n    /**\n     * Enumerates all of the documents in the `QuerySnapshot`.\n     *\n     * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n     * each document in the snapshot.\n     * @param thisArg - The `this` binding for the callback.\n     */    forEach(e, t) {\n        this._snapshot.docs.forEach((n => {\n            e.call(t, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, n.key, n, new SnapshotMetadata(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));\n        }));\n    }\n    /**\n     * Returns an array of the documents changes since the last snapshot. If this\n     * is the first snapshot, all documents will be in the list as 'added'\n     * changes.\n     *\n     * @param options - `SnapshotListenOptions` that control whether metadata-only\n     * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n     * snapshot events.\n     */    docChanges(e = {}) {\n        const t = !!e.includeMetadataChanges;\n        if (t && this._snapshot.excludesMetadataChanges) throw new FirestoreError(v.INVALID_ARGUMENT, \"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().\");\n        return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === t || (this._cachedChanges = \n        /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\n        function __PRIVATE_changesFromSnapshot(e, t) {\n            if (e._snapshot.oldDocs.isEmpty()) {\n                let t = 0;\n                return e._snapshot.docChanges.map((n => {\n                    const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, n.doc.key, n.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(n.doc.key), e._snapshot.fromCache), e.query.converter);\n                    return n.doc, {\n                        type: \"added\",\n                        doc: r,\n                        oldIndex: -1,\n                        newIndex: t++\n                    };\n                }));\n            }\n            {\n                // A `DocumentSet` that is updated incrementally as changes are applied to use\n                // to lookup the index of a document.\n                let n = e._snapshot.oldDocs;\n                return e._snapshot.docChanges.filter((e => t || 3 /* ChangeType.Metadata */ !== e.type)).map((t => {\n                    const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, t.doc.key, t.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(t.doc.key), e._snapshot.fromCache), e.query.converter);\n                    let i = -1, s = -1;\n                    return 0 /* ChangeType.Added */ !== t.type && (i = n.indexOf(t.doc.key), n = n.delete(t.doc.key)), \n                    1 /* ChangeType.Removed */ !== t.type && (n = n.add(t.doc), s = n.indexOf(t.doc.key)), \n                    {\n                        type: __PRIVATE_resultChangeType(t.type),\n                        doc: r,\n                        oldIndex: i,\n                        newIndex: s\n                    };\n                }));\n            }\n        }(this, t), this._cachedChangesIncludeMetadataChanges = t), this._cachedChanges;\n    }\n}\n\nfunction __PRIVATE_resultChangeType(e) {\n    switch (e) {\n      case 0 /* ChangeType.Added */ :\n        return \"added\";\n\n      case 2 /* ChangeType.Modified */ :\n      case 3 /* ChangeType.Metadata */ :\n        return \"modified\";\n\n      case 1 /* ChangeType.Removed */ :\n        return \"removed\";\n\n      default:\n        return fail();\n    }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */ function snapshotEqual(e, t) {\n    return e instanceof DocumentSnapshot && t instanceof DocumentSnapshot ? e._firestore === t._firestore && e._key.isEqual(t._key) && (null === e._document ? null === t._document : e._document.isEqual(t._document)) && e._converter === t._converter : e instanceof QuerySnapshot && t instanceof QuerySnapshot && (e._firestore === t._firestore && queryEqual(e.query, t.query) && e.metadata.isEqual(t.metadata) && e._snapshot.isEqual(t._snapshot));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function getDoc(e) {\n    e = __PRIVATE_cast(e, DocumentReference);\n    const t = __PRIVATE_cast(e.firestore, Firestore);\n    return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key).then((n => __PRIVATE_convertToDocSnapshot(t, e, n)));\n}\n\nclass __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter {\n    constructor(e) {\n        super(), this.firestore = e;\n    }\n    convertBytes(e) {\n        return new Bytes(e);\n    }\n    convertReference(e) {\n        const t = this.convertDocumentKey(e, this.firestore._databaseId);\n        return new DocumentReference(this.firestore, /* converter= */ null, t);\n    }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function getDocFromCache(e) {\n    e = __PRIVATE_cast(e, DocumentReference);\n    const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n    return __PRIVATE_firestoreClientGetDocumentFromLocalCache(n, e._key).then((n => new DocumentSnapshot(t, r, e._key, n, new SnapshotMetadata(null !== n && n.hasLocalMutations, \n    /* fromCache= */ !0), e.converter)));\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function getDocFromServer(e) {\n    e = __PRIVATE_cast(e, DocumentReference);\n    const t = __PRIVATE_cast(e.firestore, Firestore);\n    return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key, {\n        source: \"server\"\n    }).then((n => __PRIVATE_convertToDocSnapshot(t, e, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function getDocs(e) {\n    e = __PRIVATE_cast(e, Query);\n    const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n    return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query), __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query).then((n => new QuerySnapshot(t, r, e, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function getDocsFromCache(e) {\n    e = __PRIVATE_cast(e, Query);\n    const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n    return __PRIVATE_firestoreClientGetDocumentsFromLocalCache(n, e._query).then((n => new QuerySnapshot(t, r, e, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function getDocsFromServer(e) {\n    e = __PRIVATE_cast(e, Query);\n    const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);\n    return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query, {\n        source: \"server\"\n    }).then((n => new QuerySnapshot(t, r, e, n)));\n}\n\nfunction setDoc(e, t, n) {\n    e = __PRIVATE_cast(e, DocumentReference);\n    const r = __PRIVATE_cast(e.firestore, Firestore), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t, n);\n    return executeWrite(r, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(r), \"setDoc\", e._key, i, null !== e.converter, n).toMutation(e._key, Precondition.none()) ]);\n}\n\nfunction updateDoc(e, t, n, ...r) {\n    e = __PRIVATE_cast(e, DocumentReference);\n    const i = __PRIVATE_cast(e.firestore, Firestore), s = __PRIVATE_newUserDataReader(i);\n    let o;\n    o = \"string\" == typeof (\n    // For Compat types, we have to \"extract\" the underlying types before\n    // performing validation.\n    t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(s, \"updateDoc\", e._key, t, n, r) : __PRIVATE_parseUpdateData(s, \"updateDoc\", e._key, t);\n    return executeWrite(i, [ o.toMutation(e._key, Precondition.exists(!0)) ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */ function deleteDoc(e) {\n    return executeWrite(__PRIVATE_cast(e.firestore, Firestore), [ new __PRIVATE_DeleteMutation(e._key, Precondition.none()) ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */ function addDoc(e, t) {\n    const n = __PRIVATE_cast(e.firestore, Firestore), r = doc(e), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t);\n    return executeWrite(n, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore), \"addDoc\", r._key, i, null !== e.converter, {}).toMutation(r._key, Precondition.exists(!1)) ]).then((() => r));\n}\n\nfunction onSnapshot(e, ...t) {\n    var n, r, i;\n    e = getModularInstance(e);\n    let s = {\n        includeMetadataChanges: !1\n    }, o = 0;\n    \"object\" != typeof t[o] || __PRIVATE_isPartialObserver(t[o]) || (s = t[o], o++);\n    const _ = {\n        includeMetadataChanges: s.includeMetadataChanges\n    };\n    if (__PRIVATE_isPartialObserver(t[o])) {\n        const e = t[o];\n        t[o] = null === (n = e.next) || void 0 === n ? void 0 : n.bind(e), t[o + 1] = null === (r = e.error) || void 0 === r ? void 0 : r.bind(e), \n        t[o + 2] = null === (i = e.complete) || void 0 === i ? void 0 : i.bind(e);\n    }\n    let a, u, c;\n    if (e instanceof DocumentReference) u = __PRIVATE_cast(e.firestore, Firestore), \n    c = __PRIVATE_newQueryForPath(e._key.path), a = {\n        next: n => {\n            t[o] && t[o](__PRIVATE_convertToDocSnapshot(u, e, n));\n        },\n        error: t[o + 1],\n        complete: t[o + 2]\n    }; else {\n        const n = __PRIVATE_cast(e, Query);\n        u = __PRIVATE_cast(n.firestore, Firestore), c = n._query;\n        const r = new __PRIVATE_ExpUserDataWriter(u);\n        a = {\n            next: e => {\n                t[o] && t[o](new QuerySnapshot(u, r, n, e));\n            },\n            error: t[o + 1],\n            complete: t[o + 2]\n        }, __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query);\n    }\n    return function __PRIVATE_firestoreClientListen(e, t, n, r) {\n        const i = new __PRIVATE_AsyncObserver(r), s = new __PRIVATE_QueryListener(t, i, n);\n        return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e), s))), \n        () => {\n            i.Ca(), e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e), s)));\n        };\n    }(ensureFirestoreConfigured(u), c, _, a);\n}\n\nfunction onSnapshotsInSync(e, t) {\n    return __PRIVATE_firestoreClientAddSnapshotsInSyncListener(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), __PRIVATE_isPartialObserver(t) ? t : {\n        next: t\n    });\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */ function executeWrite(e, t) {\n    return function __PRIVATE_firestoreClientWrite(e, t) {\n        const n = new __PRIVATE_Deferred;\n        return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineWrite(await __PRIVATE_getSyncEngine(e), t, n))), \n        n.promise;\n    }(ensureFirestoreConfigured(e), t);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */ function __PRIVATE_convertToDocSnapshot(e, t, n) {\n    const r = n.docs.get(t._key), i = new __PRIVATE_ExpUserDataWriter(e);\n    return new DocumentSnapshot(e, i, t._key, r, new SnapshotMetadata(n.hasPendingWrites, n.fromCache), t.converter);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Calculates the number of documents in the result set of the given query,\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can even\n * count the documents if the result set would be prohibitively large to\n * download entirely (e.g. thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used: every request using this source necessarily involves a round trip to\n * the server.\n *\n * @param query - The query whose result set size to calculate.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */ function getCountFromServer(e) {\n    return getAggregateFromServer(e, {\n        count: count()\n    });\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query, without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, is downloaded. This\n * function can even perform aggregations of the documents if the result set\n * would be prohibitively large to download entirely (e.g. thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used: every request using this source necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set to aggregate over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n *   countOfDocs: count(),\n *   totalHours: sum('hours'),\n *   averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n * @internal TODO (sum/avg) remove when public\n */ function getAggregateFromServer(e, t) {\n    const n = __PRIVATE_cast(e.firestore, Firestore), r = ensureFirestoreConfigured(n), i = function __PRIVATE_mapToArray(e, t) {\n        const n = [];\n        for (const r in e) Object.prototype.hasOwnProperty.call(e, r) && n.push(t(e[r], r, e));\n        return n;\n    }(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e._aggregateType, e._internalFieldPath)));\n    // Run the aggregation and convert the results\n    return function __PRIVATE_firestoreClientRunAggregateQuery(e, t, n) {\n        const r = new __PRIVATE_Deferred;\n        return e.asyncQueue.enqueueAndForget((async () => {\n            // TODO (sum/avg) should we update this to use the event manager?\n            // Implement and call executeAggregateQueryViaSnapshotListener, similar\n            // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n            // above\n            try {\n                // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n                const i = await __PRIVATE_getDatastore(e);\n                r.resolve(__PRIVATE_invokeRunAggregationQueryRpc(i, t, n));\n            } catch (e) {\n                r.reject(e);\n            }\n        })), r.promise;\n    }(r, e._query, i).then((t => \n    /**\n * Converts the core aggregration result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\n    function __PRIVATE_convertToAggregateQuerySnapshot(e, t, n) {\n        const r = new __PRIVATE_ExpUserDataWriter(e);\n        return new AggregateQuerySnapshot(t, r, n);\n    }\n    /**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (n, e, t)));\n}\n\nclass __PRIVATE_MemoryLocalCacheImpl {\n    constructor(e) {\n        this.kind = \"memory\", this._onlineComponentProvider = new OnlineComponentProvider, \n        (null == e ? void 0 : e.garbageCollector) ? this._offlineComponentProvider = e.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = new MemoryOfflineComponentProvider;\n    }\n    toJSON() {\n        return {\n            kind: this.kind\n        };\n    }\n}\n\nclass __PRIVATE_PersistentLocalCacheImpl {\n    constructor(e) {\n        let t;\n        this.kind = \"persistent\", (null == e ? void 0 : e.tabManager) ? (e.tabManager._initialize(e), \n        t = e.tabManager) : (t = persistentSingleTabManager(void 0), t._initialize(e)), \n        this._onlineComponentProvider = t._onlineComponentProvider, this._offlineComponentProvider = t._offlineComponentProvider;\n    }\n    toJSON() {\n        return {\n            kind: this.kind\n        };\n    }\n}\n\nclass __PRIVATE_MemoryEagerGabageCollectorImpl {\n    constructor() {\n        this.kind = \"memoryEager\", this._offlineComponentProvider = new MemoryOfflineComponentProvider;\n    }\n    toJSON() {\n        return {\n            kind: this.kind\n        };\n    }\n}\n\nclass __PRIVATE_MemoryLruGabageCollectorImpl {\n    constructor(e) {\n        this.kind = \"memoryLru\", this._offlineComponentProvider = new __PRIVATE_LruGcMemoryOfflineComponentProvider(e);\n    }\n    toJSON() {\n        return {\n            kind: this.kind\n        };\n    }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */ function memoryEagerGarbageCollector() {\n    return new __PRIVATE_MemoryEagerGabageCollectorImpl;\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */ function memoryLruGarbageCollector(e) {\n    return new __PRIVATE_MemoryLruGabageCollectorImpl(null == e ? void 0 : e.cacheSizeBytes);\n}\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */ function memoryLocalCache(e) {\n    return new __PRIVATE_MemoryLocalCacheImpl(e);\n}\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */ function persistentLocalCache(e) {\n    return new __PRIVATE_PersistentLocalCacheImpl(e);\n}\n\nclass __PRIVATE_SingleTabManagerImpl {\n    constructor(e) {\n        this.forceOwnership = e, this.kind = \"persistentSingleTab\";\n    }\n    toJSON() {\n        return {\n            kind: this.kind\n        };\n    }\n    /**\n     * @internal\n     */    _initialize(e) {\n        this._onlineComponentProvider = new OnlineComponentProvider, this._offlineComponentProvider = new __PRIVATE_IndexedDbOfflineComponentProvider(this._onlineComponentProvider, null == e ? void 0 : e.cacheSizeBytes, this.forceOwnership);\n    }\n}\n\nclass __PRIVATE_MultiTabManagerImpl {\n    constructor() {\n        this.kind = \"PersistentMultipleTab\";\n    }\n    toJSON() {\n        return {\n            kind: this.kind\n        };\n    }\n    /**\n     * @internal\n     */    _initialize(e) {\n        this._onlineComponentProvider = new OnlineComponentProvider, this._offlineComponentProvider = new __PRIVATE_MultiTabOfflineComponentProvider(this._onlineComponentProvider, null == e ? void 0 : e.cacheSizeBytes);\n    }\n}\n\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */ function persistentSingleTabManager(e) {\n    return new __PRIVATE_SingleTabManagerImpl(null == e ? void 0 : e.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */ function persistentMultipleTabManager() {\n    return new __PRIVATE_MultiTabManagerImpl;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const we = {\n    maxAttempts: 5\n};\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nclass WriteBatch {\n    /** @hideconstructor */\n    constructor(e, t) {\n        this._firestore = e, this._commitHandler = t, this._mutations = [], this._committed = !1, \n        this._dataReader = __PRIVATE_newUserDataReader(e);\n    }\n    set(e, t, n) {\n        this._verifyNotCommitted();\n        const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, \"WriteBatch.set\", r._key, i, null !== r.converter, n);\n        return this._mutations.push(s.toMutation(r._key, Precondition.none())), this;\n    }\n    update(e, t, n, ...r) {\n        this._verifyNotCommitted();\n        const i = __PRIVATE_validateReference(e, this._firestore);\n        // For Compat types, we have to \"extract\" the underlying types before\n        // performing validation.\n                let s;\n        return s = \"string\" == typeof (t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, \"WriteBatch.update\", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, \"WriteBatch.update\", i._key, t), \n        this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this;\n    }\n    /**\n     * Deletes the document referred to by the provided {@link DocumentReference}.\n     *\n     * @param documentRef - A reference to the document to be deleted.\n     * @returns This `WriteBatch` instance. Used for chaining method calls.\n     */    delete(e) {\n        this._verifyNotCommitted();\n        const t = __PRIVATE_validateReference(e, this._firestore);\n        return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(t._key, Precondition.none())), \n        this;\n    }\n    /**\n     * Commits all of the writes in this write batch as a single atomic unit.\n     *\n     * The result of these writes will only be reflected in document reads that\n     * occur after the returned promise resolves. If the client is offline, the\n     * write fails. If you would like to see local modifications or buffer writes\n     * until the client is online, use the full Firestore SDK.\n     *\n     * @returns A `Promise` resolved once all of the writes in the batch have been\n     * successfully written to the backend as an atomic unit (note that it won't\n     * resolve while you're offline).\n     */    commit() {\n        return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();\n    }\n    _verifyNotCommitted() {\n        if (this._committed) throw new FirestoreError(v.FAILED_PRECONDITION, \"A write batch can no longer be used after commit() has been called.\");\n    }\n}\n\nfunction __PRIVATE_validateReference(e, t) {\n    if ((e = getModularInstance(e)).firestore !== t) throw new FirestoreError(v.INVALID_ARGUMENT, \"Provided document reference is from a different Firestore instance.\");\n    return e;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nclass Transaction extends class Transaction$1 {\n    /** @hideconstructor */\n    constructor(e, t) {\n        this._firestore = e, this._transaction = t, this._dataReader = __PRIVATE_newUserDataReader(e);\n    }\n    /**\n     * Reads the document referenced by the provided {@link DocumentReference}.\n     *\n     * @param documentRef - A reference to the document to be read.\n     * @returns A `DocumentSnapshot` with the read data.\n     */    get(e) {\n        const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_LiteUserDataWriter(this._firestore);\n        return this._transaction.lookup([ t._key ]).then((e => {\n            if (!e || 1 !== e.length) return fail();\n            const r = e[0];\n            if (r.isFoundDocument()) return new DocumentSnapshot$1(this._firestore, n, r.key, r, t.converter);\n            if (r.isNoDocument()) return new DocumentSnapshot$1(this._firestore, n, t._key, null, t.converter);\n            throw fail();\n        }));\n    }\n    set(e, t, n) {\n        const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, \"Transaction.set\", r._key, i, null !== r.converter, n);\n        return this._transaction.set(r._key, s), this;\n    }\n    update(e, t, n, ...r) {\n        const i = __PRIVATE_validateReference(e, this._firestore);\n        // For Compat types, we have to \"extract\" the underlying types before\n        // performing validation.\n                let s;\n        return s = \"string\" == typeof (t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, \"Transaction.update\", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, \"Transaction.update\", i._key, t), \n        this._transaction.update(i._key, s), this;\n    }\n    /**\n     * Deletes the document referred to by the provided {@link DocumentReference}.\n     *\n     * @param documentRef - A reference to the document to be deleted.\n     * @returns This `Transaction` instance. Used for chaining method calls.\n     */    delete(e) {\n        const t = __PRIVATE_validateReference(e, this._firestore);\n        return this._transaction.delete(t._key), this;\n    }\n} {\n    // This class implements the same logic as the Transaction API in the Lite SDK\n    // but is subclassed in order to return its own DocumentSnapshot types.\n    /** @hideconstructor */\n    constructor(e, t) {\n        super(e, t), this._firestore = e;\n    }\n    /**\n     * Reads the document referenced by the provided {@link DocumentReference}.\n     *\n     * @param documentRef - A reference to the document to be read.\n     * @returns A `DocumentSnapshot` with the read data.\n     */    get(e) {\n        const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_ExpUserDataWriter(this._firestore);\n        return super.get(e).then((e => new DocumentSnapshot(this._firestore, n, t._key, e._document, new SnapshotMetadata(\n        /* hasPendingWrites= */ !1, \n        /* fromCache= */ !1), t.converter)));\n    }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */ function runTransaction(e, t, n) {\n    e = __PRIVATE_cast(e, Firestore);\n    const r = Object.assign(Object.assign({}, we), n);\n    !function __PRIVATE_validateTransactionOptions(e) {\n        if (e.maxAttempts < 1) throw new FirestoreError(v.INVALID_ARGUMENT, \"Max attempts must be at least 1\");\n    }(r);\n    return function __PRIVATE_firestoreClientTransaction(e, t, n) {\n        const r = new __PRIVATE_Deferred;\n        return e.asyncQueue.enqueueAndForget((async () => {\n            const i = await __PRIVATE_getDatastore(e);\n            new __PRIVATE_TransactionRunner(e.asyncQueue, i, n, t, r).run();\n        })), r.promise;\n    }(ensureFirestoreConfigured(e), (n => t(new Transaction(e, n))), r);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */ function deleteField() {\n    return new __PRIVATE_DeleteFieldValueImpl(\"deleteField\");\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */ function serverTimestamp() {\n    return new __PRIVATE_ServerTimestampFieldValueImpl(\"serverTimestamp\");\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */ function arrayUnion(...e) {\n    // NOTE: We don't actually parse the data until it's used in set() or\n    // update() since we'd need the Firestore instance to do this.\n    return new __PRIVATE_ArrayUnionFieldValueImpl(\"arrayUnion\", e);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function arrayRemove(...e) {\n    // NOTE: We don't actually parse the data until it's used in set() or\n    // update() since we'd need the Firestore instance to do this.\n    return new __PRIVATE_ArrayRemoveFieldValueImpl(\"arrayRemove\", e);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function increment(e) {\n    return new __PRIVATE_NumericIncrementFieldValueImpl(\"increment\", e);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */ function writeBatch(e) {\n    return ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), new WriteBatch(e, (t => executeWrite(e, t)));\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function setIndexConfiguration(e, t) {\n    var n;\n    const r = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore));\n    if (!r._uninitializedComponentsProvider || \"memory\" === (null === (n = r._uninitializedComponentsProvider) || void 0 === n ? void 0 : n._offlineKind)) \n    // PORTING NOTE: We don't return an error if the user has not enabled\n    // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n    return __PRIVATE_logWarn(\"Cannot enable indexes when persistence is disabled\"), \n    Promise.resolve();\n    const i = function __PRIVATE_parseIndexes(e) {\n        const t = \"string\" == typeof e ? function __PRIVATE_tryParseJson(e) {\n            try {\n                return JSON.parse(e);\n            } catch (e) {\n                throw new FirestoreError(v.INVALID_ARGUMENT, \"Failed to parse JSON: \" + (null == e ? void 0 : e.message));\n            }\n        }(e) : e, n = [];\n        if (Array.isArray(t.indexes)) for (const e of t.indexes) {\n            const t = __PRIVATE_tryGetString(e, \"collectionGroup\"), r = [];\n            if (Array.isArray(e.fields)) for (const t of e.fields) {\n                const e = __PRIVATE_fieldPathFromDotSeparatedString(\"setIndexConfiguration\", __PRIVATE_tryGetString(t, \"fieldPath\"));\n                \"CONTAINS\" === t.arrayConfig ? r.push(new IndexSegment(e, 2 /* IndexKind.CONTAINS */)) : \"ASCENDING\" === t.order ? r.push(new IndexSegment(e, 0 /* IndexKind.ASCENDING */)) : \"DESCENDING\" === t.order && r.push(new IndexSegment(e, 1 /* IndexKind.DESCENDING */));\n            }\n            n.push(new FieldIndex(FieldIndex.UNKNOWN_ID, t, r, IndexState.empty()));\n        }\n        return n;\n    }(t);\n    return __PRIVATE_firestoreClientSetIndexConfiguration(r, i);\n}\n\nfunction __PRIVATE_tryGetString(e, t) {\n    if (\"string\" != typeof e[t]) throw new FirestoreError(v.INVALID_ARGUMENT, \"Missing string value for: \" + t);\n    return e[t];\n}\n\n/**\n * Cloud Firestore\n *\n * @packageDocumentation\n */ !function __PRIVATE_registerFirestore(e, t = !0) {\n    !function __PRIVATE_setSDKVersion(e) {\n        b = e;\n    }(SDK_VERSION), _registerComponent(new Component(\"firestore\", ((e, {instanceIdentifier: n, options: r}) => {\n        const i = e.getProvider(\"app\").getImmediate(), s = new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e.getProvider(\"auth-internal\")), new __PRIVATE_FirebaseAppCheckTokenProvider(e.getProvider(\"app-check-internal\")), function __PRIVATE_databaseIdFromApp(e, t) {\n            if (!Object.prototype.hasOwnProperty.apply(e.options, [ \"projectId\" ])) throw new FirestoreError(v.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n            return new DatabaseId(e.options.projectId, t);\n        }(i, n), i);\n        return r = Object.assign({\n            useFetchStreams: t\n        }, r), s._setSettings(r), s;\n    }), \"PUBLIC\").setMultipleInstances(!0)), registerVersion(S, \"4.1.0\", e), \n    // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n    registerVersion(S, \"4.1.0\", \"esm2017\");\n}();\n\nexport { AbstractUserDataWriter, AggregateField, AggregateQuerySnapshot, Bytes, ge as CACHE_SIZE_UNLIMITED, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, LoadBundleTask, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, SnapshotMetadata, Timestamp, Transaction, WriteBatch, ByteString as _ByteString, DatabaseId as _DatabaseId, DocumentKey as _DocumentKey, __PRIVATE_EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider, __PRIVATE_EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider, FieldPath$1 as _FieldPath, __PRIVATE_TestingHooks as _TestingHooks, __PRIVATE_cast as _cast, __PRIVATE_debugAssert as _debugAssert, __PRIVATE_isBase64Available as _isBase64Available, __PRIVATE_logWarn as _logWarn, __PRIVATE_validateIsNotUsedTogether as _validateIsNotUsedTogether, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, clearIndexedDbPersistence, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, disableNetwork, doc, documentId, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, endAt, endBefore, ensureFirestoreConfigured, executeWrite, getAggregateFromServer, getCountFromServer, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, getFirestore, increment, initializeFirestore, limit, limitToLast, loadBundle, memoryEagerGarbageCollector, memoryLocalCache, memoryLruGarbageCollector, namedQuery, onSnapshot, onSnapshotsInSync, or, orderBy, persistentLocalCache, persistentMultipleTabManager, persistentSingleTabManager, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setIndexConfiguration, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, waitForPendingWrites, where, writeBatch };\n//# sourceMappingURL=index.esm2017.js.map\n","export class AssertionError extends Error {}\n\nexport function assert(value: boolean, message: string) {\n  if (!value) {\n    throw new AssertionError(message);\n  }\n}\n\nexport function assertDefined<T>(value: T, name = 'value'): NonNullable<T> {\n  if (value == null) {\n    throw new AssertionError(`${name} is ${value}; expected to be defined`);\n  }\n  return value;\n}\n\nexport function assertClass<T>(\n  value: unknown,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  clazz: any,\n  message: string,\n): T {\n  if (value instanceof clazz) {\n    return value as T;\n  }\n  throw new AssertionError(message);\n}\n\nexport function assertStrEnum<T extends Record<string, string>>(value: string, _enum: T) {\n  const enumName = (Object.keys(_enum) as Array<keyof T>).find((k) => _enum[k] === value);\n  if (!enumName) {\n    throw new AssertionError(`${value} is not a valid instance of the required enum`);\n  }\n  return _enum[enumName];\n}\n","import {FirebaseApp} from 'firebase/app';\nimport {Firestore, connectFirestoreEmulator, getFirestore} from 'firebase/firestore';\n\nimport {assertDefined} from '../util/asserts';\n\nconst DEV_BUILD = false;\n\nexport class FirestoreState {\n  private firestore?: Firestore;\n\n  initialize(app: FirebaseApp) {\n    this.firestore = getFirestore(app);\n    if (DEV_BUILD) {\n      connectFirestoreEmulator(this.firestore, 'localhost', 8080);\n    }\n  }\n\n  get store(): Firestore {\n    return assertDefined(this.firestore, 'this.firestore');\n  }\n}\n\nexport const FIRESTORE_STATE = new FirestoreState();\n","export const ENTRY_COLLECTION_ID = 'entries';\nexport const FILE_COLLECTION_ID = 'files';\nexport const INVITE_COLLECTION_ID = 'invites';\nexport const TAG_COLLECTION_ID = 'tags';\nexport const TAG_SET_COLLECTION_ID = 'tagsets';\nexport const USER_COLLECTION_ID = 'users';\nexport const WORKSPACE_COLLECTION_ID = 'workspaces';\n","import {DocumentReference, deleteDoc, setDoc} from 'firebase/firestore';\n\nimport {assert, assertDefined} from '../util/asserts';\n\nimport {Batch} from './batch';\n\nfunction strictEqual<T>(a: T, b: T): boolean {\n  return a === b;\n}\n\nconst WORKSPACE_ID_REGEXP: RegExp = /workspaces\\/([a-zA-Z0-9]+)/;\n\nexport abstract class Entity<T extends Entity<T>> {\n  protected ref: DocumentReference<T>;\n  private _dirty: boolean;\n  private listeners = new Map<unknown, () => void>();\n  isDeleted = false;\n\n  constructor(ref: DocumentReference<T>, dirty: boolean) {\n    this.ref = ref;\n    this._dirty = dirty;\n  }\n\n  get workspaceId(): string {\n    this.checkDeleted();\n    return assertDefined(\n      assertDefined(WORKSPACE_ID_REGEXP.exec(this.ref.path), 'regexp match')[1],\n      'workspace reference',\n    );\n  }\n\n  get id(): string {\n    this.checkDeleted();\n    return this.ref.id;\n  }\n\n  get dirty(): boolean {\n    this.checkDeleted();\n    return this._dirty;\n  }\n\n  markDirty() {\n    this._dirty = true;\n    this.notify();\n  }\n\n  protected maybeMarkDirty<T>(\n    oldVal: T,\n    newVal: T,\n    comparator: (a: T, b: T) => boolean = strictEqual,\n  ) {\n    if (!comparator(oldVal, newVal)) {\n      this._dirty = true;\n      this.notify();\n    }\n  }\n\n  async write(): Promise<void> {\n    this.checkDeleted();\n    if (!this._dirty) {\n      return;\n    }\n    // Abusing the type system: just having `this` here throws a type error\n    // because firebase's typing gets confused.\n    await setDoc(this.ref, this as unknown as T);\n    this._dirty = false;\n  }\n\n  writeInBatch(batch: Batch) {\n    this.checkDeleted();\n    if (!this._dirty) {\n      return;\n    }\n    // Abusing the type system: just having `this` here throws a type error\n    // because firebase's typing gets confused.\n    batch.set(this.ref, this as unknown as T);\n    batch.afterCommit(() => {\n      this._dirty = false;\n    });\n  }\n\n  async delete(): Promise<void> {\n    this.checkDeleted();\n    await deleteDoc(this.ref);\n    this.isDeleted = true;\n  }\n\n  deleteInBatch(batch: Batch) {\n    this.checkDeleted();\n    batch.delete(this.ref);\n    batch.afterCommit(() => {\n      this.isDeleted = true;\n    });\n  }\n\n  protected checkDeleted() {\n    assert(!this.isDeleted, 'attempting to perform action on deleted entity');\n  }\n\n  listen(key: unknown, fn: () => void) {\n    this.listeners.set(key, fn);\n  }\n\n  unlisten(key: unknown) {\n    this.listeners.delete(key);\n  }\n\n  protected notify() {\n    for (const fn of this.listeners.values()) {\n      fn();\n    }\n  }\n}\n","import {UserInfo} from 'firebase/auth';\nimport {\n  DocumentData,\n  DocumentReference,\n  FirestoreDataConverter,\n  QueryDocumentSnapshot,\n  collection,\n  doc,\n  documentId,\n  getDoc,\n  getDocs,\n  query,\n  where,\n} from 'firebase/firestore';\n\nimport {FIRESTORE_STATE} from '../firebase/firestore_state';\nimport {assertStrEnum} from '../util/asserts';\n\nimport {USER_COLLECTION_ID} from './collections';\nimport {Entity} from './entity';\n\ninterface UserFirestoreData {\n  displayName: string;\n  email: string;\n  photoURL: string | null;\n  automaticTagsMode?: string;\n}\n\nexport class UserError extends Error {}\nexport class UserCreateError extends UserError {}\nexport class UserDataError extends UserError {}\nexport class UserNotFoundError extends UserError {}\n\nexport enum AutomaticTagsMode {\n  SHOW_BEFORE_CUSTOM = 'show_before_custom',\n  SHOW_AFTER_CUSTOM = 'show_after_custom',\n  DO_NOT_SHOW = 'do_not_show',\n}\n\nexport class User extends Entity<User> {\n  private _displayName: string;\n  private _email: string;\n  private _photoURL: string | null;\n  private _automaticTagsMode: AutomaticTagsMode;\n\n  private constructor(\n    ref: DocumentReference<User>,\n    dirty: boolean,\n    displayName: string,\n    email: string,\n    photoURL: string | null,\n  ) {\n    super(ref, dirty);\n    this._displayName = displayName;\n    this._email = email;\n    this._photoURL = photoURL;\n    this._automaticTagsMode = AutomaticTagsMode.SHOW_BEFORE_CUSTOM;\n  }\n\n  get displayName(): string {\n    this.checkDeleted();\n    return this._displayName;\n  }\n\n  set displayName(value: string) {\n    this.checkDeleted();\n    this.maybeMarkDirty(this._displayName, value);\n    this._displayName = value;\n  }\n\n  get email(): string {\n    this.checkDeleted();\n    return this._email;\n  }\n\n  set email(value: string) {\n    this.checkDeleted();\n    this.maybeMarkDirty(this._email, value);\n    this._email = value;\n  }\n\n  get photoURL(): string | null {\n    this.checkDeleted();\n    return this._photoURL;\n  }\n\n  set photoURL(value: string | null) {\n    this.checkDeleted();\n    this.maybeMarkDirty(this._photoURL, value);\n    this._photoURL = value;\n  }\n\n  get automaticTagsMode(): AutomaticTagsMode {\n    this.checkDeleted();\n    return this._automaticTagsMode;\n  }\n\n  set automaticTagsMode(value: AutomaticTagsMode) {\n    this.checkDeleted();\n    this.maybeMarkDirty(this._automaticTagsMode, value);\n    this._automaticTagsMode = value;\n  }\n\n  static async readByIds(userIds: string[]): Promise<Array<User>> {\n    const q = query(\n      collection(FIRESTORE_STATE.store, USER_COLLECTION_ID),\n      where(documentId(), 'in', userIds),\n    ).withConverter(USER_DATA_CONVERTER);\n    return (await getDocs(q)).docs.map((doc) => doc.data());\n  }\n\n  static async loadOrCreate(user: UserInfo): Promise<User> {\n    if (user.displayName == null || user.email == null) {\n      throw new UserDataError('User display name or email is missing.');\n    }\n    const ref = doc(FIRESTORE_STATE.store, USER_COLLECTION_ID, user.uid).withConverter(\n      USER_DATA_CONVERTER,\n    );\n    const snapshot = await getDoc(ref);\n    let u = snapshot.data();\n    if (u == null) {\n      u = new User(ref, true, user.displayName, user.email, user.photoURL);\n    } else {\n      u.displayName = user.displayName;\n      u.email = user.email;\n      u.photoURL = user.photoURL;\n    }\n    await u.write();\n    return u;\n  }\n\n  static fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData>): User {\n    const data: Partial<UserFirestoreData> = snapshot.data();\n    if (data.displayName == null) {\n      throw new UserDataError('Firestore data for User has no displayName');\n    }\n    if (data.email == null) {\n      throw new UserDataError('Firestore data for User has no email');\n    }\n    const u = new User(\n      snapshot.ref.withConverter(USER_DATA_CONVERTER),\n      false,\n      data.displayName,\n      data.email,\n      data.photoURL ?? null,\n    );\n    if (data.automaticTagsMode) {\n      u._automaticTagsMode = assertStrEnum(data.automaticTagsMode, AutomaticTagsMode);\n    }\n    return u;\n  }\n\n  toFirestore(): UserFirestoreData {\n    const data: UserFirestoreData = {\n      displayName: this._displayName,\n      email: this._email,\n      photoURL: this._photoURL,\n      automaticTagsMode: this._automaticTagsMode,\n    };\n    return data;\n  }\n}\n\nexport const USER_DATA_CONVERTER: FirestoreDataConverter<User> = {\n  toFirestore: (u: User) => u.toFirestore(),\n  fromFirestore: (snapshot: QueryDocumentSnapshot<DocumentData>) => User.fromFirestore(snapshot),\n};\n","import {FirebaseApp} from 'firebase/app';\nimport {\n  Auth,\n  User as FirebaseUser,\n  GoogleAuthProvider,\n  connectAuthEmulator,\n  getAuth,\n  onAuthStateChanged,\n  signInWithRedirect,\n  signOut,\n} from 'firebase/auth';\nimport Cookies from 'js-cookie';\n\nimport {User} from '../data/user';\nimport {assertDefined} from '../util/asserts';\n\nconst DEV_BUILD = false;\n\nexport class AuthState {\n  private auth?: Auth;\n\n  private readonly authStateChangeListeners: Array<(u: User | null) => void> = [];\n\n  private _currentUser: User | null = null;\n\n  initialize(app: FirebaseApp) {\n    this.auth = getAuth(app);\n    if (DEV_BUILD) {\n      connectAuthEmulator(this.auth, 'http://localhost:9099', {disableWarnings: true});\n    }\n    onAuthStateChanged(this.auth, async (u: FirebaseUser | null) => {\n      if (u == null) {\n        this._currentUser = null;\n      } else {\n        this._currentUser = await User.loadOrCreate(u);\n        await this.getSessionCookie();\n      }\n      for (const listener of this.authStateChangeListeners) {\n        listener(this.currentUser);\n      }\n    });\n  }\n\n  login() {\n    signInWithRedirect(assertDefined(this.auth, 'this.auth'), new GoogleAuthProvider());\n  }\n\n  logout() {\n    signOut(assertDefined(this.auth, 'this.auth'));\n    // Proactively update currentUser so that the navigation to /login doesn't get confused;\n    this._currentUser = null;\n  }\n\n  onAuthStateChange(listener: (u: User | null) => void) {\n    this.authStateChangeListeners.push(listener);\n  }\n\n  get currentUser() {\n    return this._currentUser;\n  }\n\n  async getSessionCookie() {\n    // I have no idea if this is the right way to do csrfTokens.\n    const csrfToken = (Math.random() * 100000000000000000).toString(16);\n    Cookies.set('csrfToken', csrfToken, {\n      expires: new Date(new Date().getTime() + 60 * 1000), // 1 minute\n      sameSite: 'strict',\n      secure: DEV_BUILD ? false : true,\n    });\n\n    const idToken = await assertDefined(this.auth?.currentUser, 'current user').getIdToken();\n\n    await fetch('/get_session_cookie', {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n      },\n      body: JSON.stringify({csrfToken, idToken}),\n    });\n  }\n}\n\nexport const AUTH_STATE = new AuthState();\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"10.1.0\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","import { _registerComponent, registerVersion, _getProvider, getApp } from '@firebase/app';\nimport { FirebaseError, getModularInstance, getDefaultEmulatorHostnameAndPort } from '@firebase/util';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';\r\nconst UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';\r\nfunction mapValues(\r\n// { [k: string]: unknown } is no longer a wildcard assignment target after typescript 3.5\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\no, f) {\r\n    const result = {};\r\n    for (const key in o) {\r\n        if (o.hasOwnProperty(key)) {\r\n            result[key] = f(o[key]);\r\n        }\r\n    }\r\n    return result;\r\n}\r\n/**\r\n * Takes data and encodes it in a JSON-friendly way, such that types such as\r\n * Date are preserved.\r\n * @internal\r\n * @param data - Data to encode.\r\n */\r\nfunction encode(data) {\r\n    if (data == null) {\r\n        return null;\r\n    }\r\n    if (data instanceof Number) {\r\n        data = data.valueOf();\r\n    }\r\n    if (typeof data === 'number' && isFinite(data)) {\r\n        // Any number in JS is safe to put directly in JSON and parse as a double\r\n        // without any loss of precision.\r\n        return data;\r\n    }\r\n    if (data === true || data === false) {\r\n        return data;\r\n    }\r\n    if (Object.prototype.toString.call(data) === '[object String]') {\r\n        return data;\r\n    }\r\n    if (data instanceof Date) {\r\n        return data.toISOString();\r\n    }\r\n    if (Array.isArray(data)) {\r\n        return data.map(x => encode(x));\r\n    }\r\n    if (typeof data === 'function' || typeof data === 'object') {\r\n        return mapValues(data, x => encode(x));\r\n    }\r\n    // If we got this far, the data is not encodable.\r\n    throw new Error('Data cannot be encoded in JSON: ' + data);\r\n}\r\n/**\r\n * Takes data that's been encoded in a JSON-friendly form and returns a form\r\n * with richer datatypes, such as Dates, etc.\r\n * @internal\r\n * @param json - JSON to convert.\r\n */\r\nfunction decode(json) {\r\n    if (json == null) {\r\n        return json;\r\n    }\r\n    if (json['@type']) {\r\n        switch (json['@type']) {\r\n            case LONG_TYPE:\r\n            // Fall through and handle this the same as unsigned.\r\n            case UNSIGNED_LONG_TYPE: {\r\n                // Technically, this could work return a valid number for malformed\r\n                // data if there was a number followed by garbage. But it's just not\r\n                // worth all the extra code to detect that case.\r\n                const value = Number(json['value']);\r\n                if (isNaN(value)) {\r\n                    throw new Error('Data cannot be decoded from JSON: ' + json);\r\n                }\r\n                return value;\r\n            }\r\n            default: {\r\n                throw new Error('Data cannot be decoded from JSON: ' + json);\r\n            }\r\n        }\r\n    }\r\n    if (Array.isArray(json)) {\r\n        return json.map(x => decode(x));\r\n    }\r\n    if (typeof json === 'function' || typeof json === 'object') {\r\n        return mapValues(json, x => decode(x));\r\n    }\r\n    // Anything else is safe to return.\r\n    return json;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Type constant for Firebase Functions.\r\n */\r\nconst FUNCTIONS_TYPE = 'functions';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Standard error codes for different ways a request can fail, as defined by:\r\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\r\n *\r\n * This map is used primarily to convert from a backend error code string to\r\n * a client SDK error code string, and make sure it's in the supported set.\r\n */\r\nconst errorCodeMap = {\r\n    OK: 'ok',\r\n    CANCELLED: 'cancelled',\r\n    UNKNOWN: 'unknown',\r\n    INVALID_ARGUMENT: 'invalid-argument',\r\n    DEADLINE_EXCEEDED: 'deadline-exceeded',\r\n    NOT_FOUND: 'not-found',\r\n    ALREADY_EXISTS: 'already-exists',\r\n    PERMISSION_DENIED: 'permission-denied',\r\n    UNAUTHENTICATED: 'unauthenticated',\r\n    RESOURCE_EXHAUSTED: 'resource-exhausted',\r\n    FAILED_PRECONDITION: 'failed-precondition',\r\n    ABORTED: 'aborted',\r\n    OUT_OF_RANGE: 'out-of-range',\r\n    UNIMPLEMENTED: 'unimplemented',\r\n    INTERNAL: 'internal',\r\n    UNAVAILABLE: 'unavailable',\r\n    DATA_LOSS: 'data-loss'\r\n};\r\n/**\r\n * An explicit error that can be thrown from a handler to send an error to the\r\n * client that called the function.\r\n */\r\nclass FunctionsError extends FirebaseError {\r\n    constructor(\r\n    /**\r\n     * A standard error code that will be returned to the client. This also\r\n     * determines the HTTP status code of the response, as defined in code.proto.\r\n     */\r\n    code, message, \r\n    /**\r\n     * Extra data to be converted to JSON and included in the error response.\r\n     */\r\n    details) {\r\n        super(`${FUNCTIONS_TYPE}/${code}`, message || '');\r\n        this.details = details;\r\n    }\r\n}\r\n/**\r\n * Takes an HTTP status code and returns the corresponding ErrorCode.\r\n * This is the standard HTTP status code -> error mapping defined in:\r\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\r\n *\r\n * @param status An HTTP status code.\r\n * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.\r\n */\r\nfunction codeForHTTPStatus(status) {\r\n    // Make sure any successful status is OK.\r\n    if (status >= 200 && status < 300) {\r\n        return 'ok';\r\n    }\r\n    switch (status) {\r\n        case 0:\r\n            // This can happen if the server returns 500.\r\n            return 'internal';\r\n        case 400:\r\n            return 'invalid-argument';\r\n        case 401:\r\n            return 'unauthenticated';\r\n        case 403:\r\n            return 'permission-denied';\r\n        case 404:\r\n            return 'not-found';\r\n        case 409:\r\n            return 'aborted';\r\n        case 429:\r\n            return 'resource-exhausted';\r\n        case 499:\r\n            return 'cancelled';\r\n        case 500:\r\n            return 'internal';\r\n        case 501:\r\n            return 'unimplemented';\r\n        case 503:\r\n            return 'unavailable';\r\n        case 504:\r\n            return 'deadline-exceeded';\r\n    }\r\n    return 'unknown';\r\n}\r\n/**\r\n * Takes an HTTP response and returns the corresponding Error, if any.\r\n */\r\nfunction _errorForResponse(status, bodyJSON) {\r\n    let code = codeForHTTPStatus(status);\r\n    // Start with reasonable defaults from the status code.\r\n    let description = code;\r\n    let details = undefined;\r\n    // Then look through the body for explicit details.\r\n    try {\r\n        const errorJSON = bodyJSON && bodyJSON.error;\r\n        if (errorJSON) {\r\n            const status = errorJSON.status;\r\n            if (typeof status === 'string') {\r\n                if (!errorCodeMap[status]) {\r\n                    // They must've included an unknown error code in the body.\r\n                    return new FunctionsError('internal', 'internal');\r\n                }\r\n                code = errorCodeMap[status];\r\n                // TODO(klimt): Add better default descriptions for error enums.\r\n                // The default description needs to be updated for the new code.\r\n                description = status;\r\n            }\r\n            const message = errorJSON.message;\r\n            if (typeof message === 'string') {\r\n                description = message;\r\n            }\r\n            details = errorJSON.details;\r\n            if (details !== undefined) {\r\n                details = decode(details);\r\n            }\r\n        }\r\n    }\r\n    catch (e) {\r\n        // If we couldn't parse explicit error data, that's fine.\r\n    }\r\n    if (code === 'ok') {\r\n        // Technically, there's an edge case where a developer could explicitly\r\n        // return an error code of OK, and we will treat it as success, but that\r\n        // seems reasonable.\r\n        return null;\r\n    }\r\n    return new FunctionsError(code, description, details);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Helper class to get metadata that should be included with a function call.\r\n * @internal\r\n */\r\nclass ContextProvider {\r\n    constructor(authProvider, messagingProvider, appCheckProvider) {\r\n        this.auth = null;\r\n        this.messaging = null;\r\n        this.appCheck = null;\r\n        this.auth = authProvider.getImmediate({ optional: true });\r\n        this.messaging = messagingProvider.getImmediate({\r\n            optional: true\r\n        });\r\n        if (!this.auth) {\r\n            authProvider.get().then(auth => (this.auth = auth), () => {\r\n                /* get() never rejects */\r\n            });\r\n        }\r\n        if (!this.messaging) {\r\n            messagingProvider.get().then(messaging => (this.messaging = messaging), () => {\r\n                /* get() never rejects */\r\n            });\r\n        }\r\n        if (!this.appCheck) {\r\n            appCheckProvider.get().then(appCheck => (this.appCheck = appCheck), () => {\r\n                /* get() never rejects */\r\n            });\r\n        }\r\n    }\r\n    async getAuthToken() {\r\n        if (!this.auth) {\r\n            return undefined;\r\n        }\r\n        try {\r\n            const token = await this.auth.getToken();\r\n            return token === null || token === void 0 ? void 0 : token.accessToken;\r\n        }\r\n        catch (e) {\r\n            // If there's any error when trying to get the auth token, leave it off.\r\n            return undefined;\r\n        }\r\n    }\r\n    async getMessagingToken() {\r\n        if (!this.messaging ||\r\n            !('Notification' in self) ||\r\n            Notification.permission !== 'granted') {\r\n            return undefined;\r\n        }\r\n        try {\r\n            return await this.messaging.getToken();\r\n        }\r\n        catch (e) {\r\n            // We don't warn on this, because it usually means messaging isn't set up.\r\n            // console.warn('Failed to retrieve instance id token.', e);\r\n            // If there's any error when trying to get the token, leave it off.\r\n            return undefined;\r\n        }\r\n    }\r\n    async getAppCheckToken(limitedUseAppCheckTokens) {\r\n        if (this.appCheck) {\r\n            const result = limitedUseAppCheckTokens\r\n                ? await this.appCheck.getLimitedUseToken()\r\n                : await this.appCheck.getToken();\r\n            if (result.error) {\r\n                // Do not send the App Check header to the functions endpoint if\r\n                // there was an error from the App Check exchange endpoint. The App\r\n                // Check SDK will already have logged the error to console.\r\n                return null;\r\n            }\r\n            return result.token;\r\n        }\r\n        return null;\r\n    }\r\n    async getContext(limitedUseAppCheckTokens) {\r\n        const authToken = await this.getAuthToken();\r\n        const messagingToken = await this.getMessagingToken();\r\n        const appCheckToken = await this.getAppCheckToken(limitedUseAppCheckTokens);\r\n        return { authToken, messagingToken, appCheckToken };\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_REGION = 'us-central1';\r\n/**\r\n * Returns a Promise that will be rejected after the given duration.\r\n * The error will be of type FunctionsError.\r\n *\r\n * @param millis Number of milliseconds to wait before rejecting.\r\n */\r\nfunction failAfter(millis) {\r\n    // Node timers and browser timers are fundamentally incompatible, but we\r\n    // don't care about the value here\r\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n    let timer = null;\r\n    return {\r\n        promise: new Promise((_, reject) => {\r\n            timer = setTimeout(() => {\r\n                reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));\r\n            }, millis);\r\n        }),\r\n        cancel: () => {\r\n            if (timer) {\r\n                clearTimeout(timer);\r\n            }\r\n        }\r\n    };\r\n}\r\n/**\r\n * The main class for the Firebase Functions SDK.\r\n * @internal\r\n */\r\nclass FunctionsService {\r\n    /**\r\n     * Creates a new Functions service for the given app.\r\n     * @param app - The FirebaseApp to use.\r\n     */\r\n    constructor(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain = DEFAULT_REGION, fetchImpl) {\r\n        this.app = app;\r\n        this.fetchImpl = fetchImpl;\r\n        this.emulatorOrigin = null;\r\n        this.contextProvider = new ContextProvider(authProvider, messagingProvider, appCheckProvider);\r\n        // Cancels all ongoing requests when resolved.\r\n        this.cancelAllRequests = new Promise(resolve => {\r\n            this.deleteService = () => {\r\n                return Promise.resolve(resolve());\r\n            };\r\n        });\r\n        // Resolve the region or custom domain overload by attempting to parse it.\r\n        try {\r\n            const url = new URL(regionOrCustomDomain);\r\n            this.customDomain = url.origin;\r\n            this.region = DEFAULT_REGION;\r\n        }\r\n        catch (e) {\r\n            this.customDomain = null;\r\n            this.region = regionOrCustomDomain;\r\n        }\r\n    }\r\n    _delete() {\r\n        return this.deleteService();\r\n    }\r\n    /**\r\n     * Returns the URL for a callable with the given name.\r\n     * @param name - The name of the callable.\r\n     * @internal\r\n     */\r\n    _url(name) {\r\n        const projectId = this.app.options.projectId;\r\n        if (this.emulatorOrigin !== null) {\r\n            const origin = this.emulatorOrigin;\r\n            return `${origin}/${projectId}/${this.region}/${name}`;\r\n        }\r\n        if (this.customDomain !== null) {\r\n            return `${this.customDomain}/${name}`;\r\n        }\r\n        return `https://${this.region}-${projectId}.cloudfunctions.net/${name}`;\r\n    }\r\n}\r\n/**\r\n * Modify this instance to communicate with the Cloud Functions emulator.\r\n *\r\n * Note: this must be called before this instance has been used to do any operations.\r\n *\r\n * @param host The emulator host (ex: localhost)\r\n * @param port The emulator port (ex: 5001)\r\n * @public\r\n */\r\nfunction connectFunctionsEmulator$1(functionsInstance, host, port) {\r\n    functionsInstance.emulatorOrigin = `http://${host}:${port}`;\r\n}\r\n/**\r\n * Returns a reference to the callable https trigger with the given name.\r\n * @param name - The name of the trigger.\r\n * @public\r\n */\r\nfunction httpsCallable$1(functionsInstance, name, options) {\r\n    return (data => {\r\n        return call(functionsInstance, name, data, options || {});\r\n    });\r\n}\r\n/**\r\n * Returns a reference to the callable https trigger with the given url.\r\n * @param url - The url of the trigger.\r\n * @public\r\n */\r\nfunction httpsCallableFromURL$1(functionsInstance, url, options) {\r\n    return (data => {\r\n        return callAtURL(functionsInstance, url, data, options || {});\r\n    });\r\n}\r\n/**\r\n * Does an HTTP POST and returns the completed response.\r\n * @param url The url to post to.\r\n * @param body The JSON body of the post.\r\n * @param headers The HTTP headers to include in the request.\r\n * @return A Promise that will succeed when the request finishes.\r\n */\r\nasync function postJSON(url, body, headers, fetchImpl) {\r\n    headers['Content-Type'] = 'application/json';\r\n    let response;\r\n    try {\r\n        response = await fetchImpl(url, {\r\n            method: 'POST',\r\n            body: JSON.stringify(body),\r\n            headers\r\n        });\r\n    }\r\n    catch (e) {\r\n        // This could be an unhandled error on the backend, or it could be a\r\n        // network error. There's no way to know, since an unhandled error on the\r\n        // backend will fail to set the proper CORS header, and thus will be\r\n        // treated as a network error by fetch.\r\n        return {\r\n            status: 0,\r\n            json: null\r\n        };\r\n    }\r\n    let json = null;\r\n    try {\r\n        json = await response.json();\r\n    }\r\n    catch (e) {\r\n        // If we fail to parse JSON, it will fail the same as an empty body.\r\n    }\r\n    return {\r\n        status: response.status,\r\n        json\r\n    };\r\n}\r\n/**\r\n * Calls a callable function asynchronously and returns the result.\r\n * @param name The name of the callable trigger.\r\n * @param data The data to pass as params to the function.s\r\n */\r\nfunction call(functionsInstance, name, data, options) {\r\n    const url = functionsInstance._url(name);\r\n    return callAtURL(functionsInstance, url, data, options);\r\n}\r\n/**\r\n * Calls a callable function asynchronously and returns the result.\r\n * @param url The url of the callable trigger.\r\n * @param data The data to pass as params to the function.s\r\n */\r\nasync function callAtURL(functionsInstance, url, data, options) {\r\n    // Encode any special types, such as dates, in the input data.\r\n    data = encode(data);\r\n    const body = { data };\r\n    // Add a header for the authToken.\r\n    const headers = {};\r\n    const context = await functionsInstance.contextProvider.getContext(options.limitedUseAppCheckTokens);\r\n    if (context.authToken) {\r\n        headers['Authorization'] = 'Bearer ' + context.authToken;\r\n    }\r\n    if (context.messagingToken) {\r\n        headers['Firebase-Instance-ID-Token'] = context.messagingToken;\r\n    }\r\n    if (context.appCheckToken !== null) {\r\n        headers['X-Firebase-AppCheck'] = context.appCheckToken;\r\n    }\r\n    // Default timeout to 70s, but let the options override it.\r\n    const timeout = options.timeout || 70000;\r\n    const failAfterHandle = failAfter(timeout);\r\n    const response = await Promise.race([\r\n        postJSON(url, body, headers, functionsInstance.fetchImpl),\r\n        failAfterHandle.promise,\r\n        functionsInstance.cancelAllRequests\r\n    ]);\r\n    // Always clear the failAfter timeout\r\n    failAfterHandle.cancel();\r\n    // If service was deleted, interrupted response throws an error.\r\n    if (!response) {\r\n        throw new FunctionsError('cancelled', 'Firebase Functions instance was deleted.');\r\n    }\r\n    // Check for an error status, regardless of http status.\r\n    const error = _errorForResponse(response.status, response.json);\r\n    if (error) {\r\n        throw error;\r\n    }\r\n    if (!response.json) {\r\n        throw new FunctionsError('internal', 'Response is not valid JSON object.');\r\n    }\r\n    let responseData = response.json.data;\r\n    // TODO(klimt): For right now, allow \"result\" instead of \"data\", for\r\n    // backwards compatibility.\r\n    if (typeof responseData === 'undefined') {\r\n        responseData = response.json.result;\r\n    }\r\n    if (typeof responseData === 'undefined') {\r\n        // Consider the response malformed.\r\n        throw new FunctionsError('internal', 'Response is missing data field.');\r\n    }\r\n    // Decode any special types, such as dates, in the returned data.\r\n    const decodedData = decode(responseData);\r\n    return { data: decodedData };\r\n}\n\nconst name = \"@firebase/functions\";\nconst version = \"0.10.0\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst AUTH_INTERNAL_NAME = 'auth-internal';\r\nconst APP_CHECK_INTERNAL_NAME = 'app-check-internal';\r\nconst MESSAGING_INTERNAL_NAME = 'messaging-internal';\r\nfunction registerFunctions(fetchImpl, variant) {\r\n    const factory = (container, { instanceIdentifier: regionOrCustomDomain }) => {\r\n        // Dependencies\r\n        const app = container.getProvider('app').getImmediate();\r\n        const authProvider = container.getProvider(AUTH_INTERNAL_NAME);\r\n        const messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);\r\n        const appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);\r\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n        return new FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl);\r\n    };\r\n    _registerComponent(new Component(FUNCTIONS_TYPE, factory, \"PUBLIC\" /* ComponentType.PUBLIC */).setMultipleInstances(true));\r\n    registerVersion(name, version, variant);\r\n    // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n    registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a {@link Functions} instance for the given app.\r\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\r\n * @param regionOrCustomDomain - one of:\r\n *   a) The region the callable functions are located in (ex: us-central1)\r\n *   b) A custom domain hosting the callable functions (ex: https://mydomain.com)\r\n * @public\r\n */\r\nfunction getFunctions(app = getApp(), regionOrCustomDomain = DEFAULT_REGION) {\r\n    // Dependencies\r\n    const functionsProvider = _getProvider(getModularInstance(app), FUNCTIONS_TYPE);\r\n    const functionsInstance = functionsProvider.getImmediate({\r\n        identifier: regionOrCustomDomain\r\n    });\r\n    const emulator = getDefaultEmulatorHostnameAndPort('functions');\r\n    if (emulator) {\r\n        connectFunctionsEmulator(functionsInstance, ...emulator);\r\n    }\r\n    return functionsInstance;\r\n}\r\n/**\r\n * Modify this instance to communicate with the Cloud Functions emulator.\r\n *\r\n * Note: this must be called before this instance has been used to do any operations.\r\n *\r\n * @param host - The emulator host (ex: localhost)\r\n * @param port - The emulator port (ex: 5001)\r\n * @public\r\n */\r\nfunction connectFunctionsEmulator(functionsInstance, host, port) {\r\n    connectFunctionsEmulator$1(getModularInstance(functionsInstance), host, port);\r\n}\r\n/**\r\n * Returns a reference to the callable HTTPS trigger with the given name.\r\n * @param name - The name of the trigger.\r\n * @public\r\n */\r\nfunction httpsCallable(functionsInstance, name, options) {\r\n    return httpsCallable$1(getModularInstance(functionsInstance), name, options);\r\n}\r\n/**\r\n * Returns a reference to the callable HTTPS trigger with the specified url.\r\n * @param url - The url of the trigger.\r\n * @public\r\n */\r\nfunction httpsCallableFromURL(functionsInstance, url, options) {\r\n    return httpsCallableFromURL$1(getModularInstance(functionsInstance), url, options);\r\n}\n\n/**\r\n * Cloud Functions for Firebase\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterFunctions(fetch.bind(self));\n\nexport { connectFunctionsEmulator, getFunctions, httpsCallable, httpsCallableFromURL };\n//# sourceMappingURL=index.esm2017.js.map\n","// these aren't really private, but nor are they really useful to document\n\n/**\n * @private\n */\nclass LuxonError extends Error {}\n\n/**\n * @private\n */\nexport class InvalidDateTimeError extends LuxonError {\n  constructor(reason) {\n    super(`Invalid DateTime: ${reason.toMessage()}`);\n  }\n}\n\n/**\n * @private\n */\nexport class InvalidIntervalError extends LuxonError {\n  constructor(reason) {\n    super(`Invalid Interval: ${reason.toMessage()}`);\n  }\n}\n\n/**\n * @private\n */\nexport class InvalidDurationError extends LuxonError {\n  constructor(reason) {\n    super(`Invalid Duration: ${reason.toMessage()}`);\n  }\n}\n\n/**\n * @private\n */\nexport class ConflictingSpecificationError extends LuxonError {}\n\n/**\n * @private\n */\nexport class InvalidUnitError extends LuxonError {\n  constructor(unit) {\n    super(`Invalid unit ${unit}`);\n  }\n}\n\n/**\n * @private\n */\nexport class InvalidArgumentError extends LuxonError {}\n\n/**\n * @private\n */\nexport class ZoneIsAbstractError extends LuxonError {\n  constructor() {\n    super(\"Zone is an abstract class\");\n  }\n}\n","/**\n * @private\n */\n\nconst n = \"numeric\",\n  s = \"short\",\n  l = \"long\";\n\nexport const DATE_SHORT = {\n  year: n,\n  month: n,\n  day: n,\n};\n\nexport const DATE_MED = {\n  year: n,\n  month: s,\n  day: n,\n};\n\nexport const DATE_MED_WITH_WEEKDAY = {\n  year: n,\n  month: s,\n  day: n,\n  weekday: s,\n};\n\nexport const DATE_FULL = {\n  year: n,\n  month: l,\n  day: n,\n};\n\nexport const DATE_HUGE = {\n  year: n,\n  month: l,\n  day: n,\n  weekday: l,\n};\n\nexport const TIME_SIMPLE = {\n  hour: n,\n  minute: n,\n};\n\nexport const TIME_WITH_SECONDS = {\n  hour: n,\n  minute: n,\n  second: n,\n};\n\nexport const TIME_WITH_SHORT_OFFSET = {\n  hour: n,\n  minute: n,\n  second: n,\n  timeZoneName: s,\n};\n\nexport const TIME_WITH_LONG_OFFSET = {\n  hour: n,\n  minute: n,\n  second: n,\n  timeZoneName: l,\n};\n\nexport const TIME_24_SIMPLE = {\n  hour: n,\n  minute: n,\n  hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SECONDS = {\n  hour: n,\n  minute: n,\n  second: n,\n  hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SHORT_OFFSET = {\n  hour: n,\n  minute: n,\n  second: n,\n  hourCycle: \"h23\",\n  timeZoneName: s,\n};\n\nexport const TIME_24_WITH_LONG_OFFSET = {\n  hour: n,\n  minute: n,\n  second: n,\n  hourCycle: \"h23\",\n  timeZoneName: l,\n};\n\nexport const DATETIME_SHORT = {\n  year: n,\n  month: n,\n  day: n,\n  hour: n,\n  minute: n,\n};\n\nexport const DATETIME_SHORT_WITH_SECONDS = {\n  year: n,\n  month: n,\n  day: n,\n  hour: n,\n  minute: n,\n  second: n,\n};\n\nexport const DATETIME_MED = {\n  year: n,\n  month: s,\n  day: n,\n  hour: n,\n  minute: n,\n};\n\nexport const DATETIME_MED_WITH_SECONDS = {\n  year: n,\n  month: s,\n  day: n,\n  hour: n,\n  minute: n,\n  second: n,\n};\n\nexport const DATETIME_MED_WITH_WEEKDAY = {\n  year: n,\n  month: s,\n  day: n,\n  weekday: s,\n  hour: n,\n  minute: n,\n};\n\nexport const DATETIME_FULL = {\n  year: n,\n  month: l,\n  day: n,\n  hour: n,\n  minute: n,\n  timeZoneName: s,\n};\n\nexport const DATETIME_FULL_WITH_SECONDS = {\n  year: n,\n  month: l,\n  day: n,\n  hour: n,\n  minute: n,\n  second: n,\n  timeZoneName: s,\n};\n\nexport const DATETIME_HUGE = {\n  year: n,\n  month: l,\n  day: n,\n  weekday: l,\n  hour: n,\n  minute: n,\n  timeZoneName: l,\n};\n\nexport const DATETIME_HUGE_WITH_SECONDS = {\n  year: n,\n  month: l,\n  day: n,\n  weekday: l,\n  hour: n,\n  minute: n,\n  second: n,\n  timeZoneName: l,\n};\n","import { ZoneIsAbstractError } from \"./errors.js\";\n\n/**\n * @interface\n */\nexport default class Zone {\n  /**\n   * The type of zone\n   * @abstract\n   * @type {string}\n   */\n  get type() {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * The name of this zone.\n   * @abstract\n   * @type {string}\n   */\n  get name() {\n    throw new ZoneIsAbstractError();\n  }\n\n  get ianaName() {\n    return this.name;\n  }\n\n  /**\n   * Returns whether the offset is known to be fixed for the whole year.\n   * @abstract\n   * @type {boolean}\n   */\n  get isUniversal() {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Returns the offset's common name (such as EST) at the specified timestamp\n   * @abstract\n   * @param {number} ts - Epoch milliseconds for which to get the name\n   * @param {Object} opts - Options to affect the format\n   * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.\n   * @param {string} opts.locale - What locale to return the offset name in.\n   * @return {string}\n   */\n  offsetName(ts, opts) {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Returns the offset's value as a string\n   * @abstract\n   * @param {number} ts - Epoch milliseconds for which to get the offset\n   * @param {string} format - What style of offset to return.\n   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n   * @return {string}\n   */\n  formatOffset(ts, format) {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Return the offset in minutes for this zone at the specified timestamp.\n   * @abstract\n   * @param {number} ts - Epoch milliseconds for which to compute the offset\n   * @return {number}\n   */\n  offset(ts) {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Return whether this Zone is equal to another zone\n   * @abstract\n   * @param {Zone} otherZone - the zone to compare\n   * @return {boolean}\n   */\n  equals(otherZone) {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Return whether this Zone is valid.\n   * @abstract\n   * @type {boolean}\n   */\n  get isValid() {\n    throw new ZoneIsAbstractError();\n  }\n}\n","import { formatOffset, parseZoneInfo } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * Represents the local zone for this JavaScript environment.\n * @implements {Zone}\n */\nexport default class SystemZone extends Zone {\n  /**\n   * Get a singleton instance of the local zone\n   * @return {SystemZone}\n   */\n  static get instance() {\n    if (singleton === null) {\n      singleton = new SystemZone();\n    }\n    return singleton;\n  }\n\n  /** @override **/\n  get type() {\n    return \"system\";\n  }\n\n  /** @override **/\n  get name() {\n    return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n  }\n\n  /** @override **/\n  get isUniversal() {\n    return false;\n  }\n\n  /** @override **/\n  offsetName(ts, { format, locale }) {\n    return parseZoneInfo(ts, format, locale);\n  }\n\n  /** @override **/\n  formatOffset(ts, format) {\n    return formatOffset(this.offset(ts), format);\n  }\n\n  /** @override **/\n  offset(ts) {\n    return -new Date(ts).getTimezoneOffset();\n  }\n\n  /** @override **/\n  equals(otherZone) {\n    return otherZone.type === \"system\";\n  }\n\n  /** @override **/\n  get isValid() {\n    return true;\n  }\n}\n","import { formatOffset, parseZoneInfo, isUndefined, objToLocalTS } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet dtfCache = {};\nfunction makeDTF(zone) {\n  if (!dtfCache[zone]) {\n    dtfCache[zone] = new Intl.DateTimeFormat(\"en-US\", {\n      hour12: false,\n      timeZone: zone,\n      year: \"numeric\",\n      month: \"2-digit\",\n      day: \"2-digit\",\n      hour: \"2-digit\",\n      minute: \"2-digit\",\n      second: \"2-digit\",\n      era: \"short\",\n    });\n  }\n  return dtfCache[zone];\n}\n\nconst typeToPos = {\n  year: 0,\n  month: 1,\n  day: 2,\n  era: 3,\n  hour: 4,\n  minute: 5,\n  second: 6,\n};\n\nfunction hackyOffset(dtf, date) {\n  const formatted = dtf.format(date).replace(/\\u200E/g, \"\"),\n    parsed = /(\\d+)\\/(\\d+)\\/(\\d+) (AD|BC),? (\\d+):(\\d+):(\\d+)/.exec(formatted),\n    [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;\n  return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];\n}\n\nfunction partsOffset(dtf, date) {\n  const formatted = dtf.formatToParts(date);\n  const filled = [];\n  for (let i = 0; i < formatted.length; i++) {\n    const { type, value } = formatted[i];\n    const pos = typeToPos[type];\n\n    if (type === \"era\") {\n      filled[pos] = value;\n    } else if (!isUndefined(pos)) {\n      filled[pos] = parseInt(value, 10);\n    }\n  }\n  return filled;\n}\n\nlet ianaZoneCache = {};\n/**\n * A zone identified by an IANA identifier, like America/New_York\n * @implements {Zone}\n */\nexport default class IANAZone extends Zone {\n  /**\n   * @param {string} name - Zone name\n   * @return {IANAZone}\n   */\n  static create(name) {\n    if (!ianaZoneCache[name]) {\n      ianaZoneCache[name] = new IANAZone(name);\n    }\n    return ianaZoneCache[name];\n  }\n\n  /**\n   * Reset local caches. Should only be necessary in testing scenarios.\n   * @return {void}\n   */\n  static resetCache() {\n    ianaZoneCache = {};\n    dtfCache = {};\n  }\n\n  /**\n   * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.\n   * @param {string} s - The string to check validity on\n   * @example IANAZone.isValidSpecifier(\"America/New_York\") //=> true\n   * @example IANAZone.isValidSpecifier(\"Sport~~blorp\") //=> false\n   * @deprecated This method returns false for some valid IANA names. Use isValidZone instead.\n   * @return {boolean}\n   */\n  static isValidSpecifier(s) {\n    return this.isValidZone(s);\n  }\n\n  /**\n   * Returns whether the provided string identifies a real zone\n   * @param {string} zone - The string to check\n   * @example IANAZone.isValidZone(\"America/New_York\") //=> true\n   * @example IANAZone.isValidZone(\"Fantasia/Castle\") //=> false\n   * @example IANAZone.isValidZone(\"Sport~~blorp\") //=> false\n   * @return {boolean}\n   */\n  static isValidZone(zone) {\n    if (!zone) {\n      return false;\n    }\n    try {\n      new Intl.DateTimeFormat(\"en-US\", { timeZone: zone }).format();\n      return true;\n    } catch (e) {\n      return false;\n    }\n  }\n\n  constructor(name) {\n    super();\n    /** @private **/\n    this.zoneName = name;\n    /** @private **/\n    this.valid = IANAZone.isValidZone(name);\n  }\n\n  /** @override **/\n  get type() {\n    return \"iana\";\n  }\n\n  /** @override **/\n  get name() {\n    return this.zoneName;\n  }\n\n  /** @override **/\n  get isUniversal() {\n    return false;\n  }\n\n  /** @override **/\n  offsetName(ts, { format, locale }) {\n    return parseZoneInfo(ts, format, locale, this.name);\n  }\n\n  /** @override **/\n  formatOffset(ts, format) {\n    return formatOffset(this.offset(ts), format);\n  }\n\n  /** @override **/\n  offset(ts) {\n    const date = new Date(ts);\n\n    if (isNaN(date)) return NaN;\n\n    const dtf = makeDTF(this.name);\n    let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts\n      ? partsOffset(dtf, date)\n      : hackyOffset(dtf, date);\n\n    if (adOrBc === \"BC\") {\n      year = -Math.abs(year) + 1;\n    }\n\n    // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat\n    const adjustedHour = hour === 24 ? 0 : hour;\n\n    const asUTC = objToLocalTS({\n      year,\n      month,\n      day,\n      hour: adjustedHour,\n      minute,\n      second,\n      millisecond: 0,\n    });\n\n    let asTS = +date;\n    const over = asTS % 1000;\n    asTS -= over >= 0 ? over : 1000 + over;\n    return (asUTC - asTS) / (60 * 1000);\n  }\n\n  /** @override **/\n  equals(otherZone) {\n    return otherZone.type === \"iana\" && otherZone.name === this.name;\n  }\n\n  /** @override **/\n  get isValid() {\n    return this.valid;\n  }\n}\n","import { padStart, roundTo, hasRelative, formatOffset } from \"./util.js\";\nimport * as English from \"./english.js\";\nimport Settings from \"../settings.js\";\nimport DateTime from \"../datetime.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n// todo - remap caching\n\nlet intlLFCache = {};\nfunction getCachedLF(locString, opts = {}) {\n  const key = JSON.stringify([locString, opts]);\n  let dtf = intlLFCache[key];\n  if (!dtf) {\n    dtf = new Intl.ListFormat(locString, opts);\n    intlLFCache[key] = dtf;\n  }\n  return dtf;\n}\n\nlet intlDTCache = {};\nfunction getCachedDTF(locString, opts = {}) {\n  const key = JSON.stringify([locString, opts]);\n  let dtf = intlDTCache[key];\n  if (!dtf) {\n    dtf = new Intl.DateTimeFormat(locString, opts);\n    intlDTCache[key] = dtf;\n  }\n  return dtf;\n}\n\nlet intlNumCache = {};\nfunction getCachedINF(locString, opts = {}) {\n  const key = JSON.stringify([locString, opts]);\n  let inf = intlNumCache[key];\n  if (!inf) {\n    inf = new Intl.NumberFormat(locString, opts);\n    intlNumCache[key] = inf;\n  }\n  return inf;\n}\n\nlet intlRelCache = {};\nfunction getCachedRTF(locString, opts = {}) {\n  const { base, ...cacheKeyOpts } = opts; // exclude `base` from the options\n  const key = JSON.stringify([locString, cacheKeyOpts]);\n  let inf = intlRelCache[key];\n  if (!inf) {\n    inf = new Intl.RelativeTimeFormat(locString, opts);\n    intlRelCache[key] = inf;\n  }\n  return inf;\n}\n\nlet sysLocaleCache = null;\nfunction systemLocale() {\n  if (sysLocaleCache) {\n    return sysLocaleCache;\n  } else {\n    sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;\n    return sysLocaleCache;\n  }\n}\n\nfunction parseLocaleString(localeStr) {\n  // I really want to avoid writing a BCP 47 parser\n  // see, e.g. https://github.com/wooorm/bcp-47\n  // Instead, we'll do this:\n\n  // a) if the string has no -u extensions, just leave it alone\n  // b) if it does, use Intl to resolve everything\n  // c) if Intl fails, try again without the -u\n\n  // private subtags and unicode subtags have ordering requirements,\n  // and we're not properly parsing this, so just strip out the\n  // private ones if they exist.\n  const xIndex = localeStr.indexOf(\"-x-\");\n  if (xIndex !== -1) {\n    localeStr = localeStr.substring(0, xIndex);\n  }\n\n  const uIndex = localeStr.indexOf(\"-u-\");\n  if (uIndex === -1) {\n    return [localeStr];\n  } else {\n    let options;\n    let selectedStr;\n    try {\n      options = getCachedDTF(localeStr).resolvedOptions();\n      selectedStr = localeStr;\n    } catch (e) {\n      const smaller = localeStr.substring(0, uIndex);\n      options = getCachedDTF(smaller).resolvedOptions();\n      selectedStr = smaller;\n    }\n\n    const { numberingSystem, calendar } = options;\n    return [selectedStr, numberingSystem, calendar];\n  }\n}\n\nfunction intlConfigString(localeStr, numberingSystem, outputCalendar) {\n  if (outputCalendar || numberingSystem) {\n    if (!localeStr.includes(\"-u-\")) {\n      localeStr += \"-u\";\n    }\n\n    if (outputCalendar) {\n      localeStr += `-ca-${outputCalendar}`;\n    }\n\n    if (numberingSystem) {\n      localeStr += `-nu-${numberingSystem}`;\n    }\n    return localeStr;\n  } else {\n    return localeStr;\n  }\n}\n\nfunction mapMonths(f) {\n  const ms = [];\n  for (let i = 1; i <= 12; i++) {\n    const dt = DateTime.utc(2016, i, 1);\n    ms.push(f(dt));\n  }\n  return ms;\n}\n\nfunction mapWeekdays(f) {\n  const ms = [];\n  for (let i = 1; i <= 7; i++) {\n    const dt = DateTime.utc(2016, 11, 13 + i);\n    ms.push(f(dt));\n  }\n  return ms;\n}\n\nfunction listStuff(loc, length, defaultOK, englishFn, intlFn) {\n  const mode = loc.listingMode(defaultOK);\n\n  if (mode === \"error\") {\n    return null;\n  } else if (mode === \"en\") {\n    return englishFn(length);\n  } else {\n    return intlFn(length);\n  }\n}\n\nfunction supportsFastNumbers(loc) {\n  if (loc.numberingSystem && loc.numberingSystem !== \"latn\") {\n    return false;\n  } else {\n    return (\n      loc.numberingSystem === \"latn\" ||\n      !loc.locale ||\n      loc.locale.startsWith(\"en\") ||\n      new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === \"latn\"\n    );\n  }\n}\n\n/**\n * @private\n */\n\nclass PolyNumberFormatter {\n  constructor(intl, forceSimple, opts) {\n    this.padTo = opts.padTo || 0;\n    this.floor = opts.floor || false;\n\n    const { padTo, floor, ...otherOpts } = opts;\n\n    if (!forceSimple || Object.keys(otherOpts).length > 0) {\n      const intlOpts = { useGrouping: false, ...opts };\n      if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;\n      this.inf = getCachedINF(intl, intlOpts);\n    }\n  }\n\n  format(i) {\n    if (this.inf) {\n      const fixed = this.floor ? Math.floor(i) : i;\n      return this.inf.format(fixed);\n    } else {\n      // to match the browser's numberformatter defaults\n      const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);\n      return padStart(fixed, this.padTo);\n    }\n  }\n}\n\n/**\n * @private\n */\n\nclass PolyDateFormatter {\n  constructor(dt, intl, opts) {\n    this.opts = opts;\n    this.originalZone = undefined;\n\n    let z = undefined;\n    if (this.opts.timeZone) {\n      // Don't apply any workarounds if a timeZone is explicitly provided in opts\n      this.dt = dt;\n    } else if (dt.zone.type === \"fixed\") {\n      // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.\n      // That is why fixed-offset TZ is set to that unless it is:\n      // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.\n      // 2. Unsupported by the browser:\n      //    - some do not support Etc/\n      //    - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata\n      const gmtOffset = -1 * (dt.offset / 60);\n      const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;\n      if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {\n        z = offsetZ;\n        this.dt = dt;\n      } else {\n        // Not all fixed-offset zones like Etc/+4:30 are present in tzdata so\n        // we manually apply the offset and substitute the zone as needed.\n        z = \"UTC\";\n        this.dt = dt.offset === 0 ? dt : dt.setZone(\"UTC\").plus({ minutes: dt.offset });\n        this.originalZone = dt.zone;\n      }\n    } else if (dt.zone.type === \"system\") {\n      this.dt = dt;\n    } else if (dt.zone.type === \"iana\") {\n      this.dt = dt;\n      z = dt.zone.name;\n    } else {\n      // Custom zones can have any offset / offsetName so we just manually\n      // apply the offset and substitute the zone as needed.\n      z = \"UTC\";\n      this.dt = dt.setZone(\"UTC\").plus({ minutes: dt.offset });\n      this.originalZone = dt.zone;\n    }\n\n    const intlOpts = { ...this.opts };\n    intlOpts.timeZone = intlOpts.timeZone || z;\n    this.dtf = getCachedDTF(intl, intlOpts);\n  }\n\n  format() {\n    if (this.originalZone) {\n      // If we have to substitute in the actual zone name, we have to use\n      // formatToParts so that the timezone can be replaced.\n      return this.formatToParts()\n        .map(({ value }) => value)\n        .join(\"\");\n    }\n    return this.dtf.format(this.dt.toJSDate());\n  }\n\n  formatToParts() {\n    const parts = this.dtf.formatToParts(this.dt.toJSDate());\n    if (this.originalZone) {\n      return parts.map((part) => {\n        if (part.type === \"timeZoneName\") {\n          const offsetName = this.originalZone.offsetName(this.dt.ts, {\n            locale: this.dt.locale,\n            format: this.opts.timeZoneName,\n          });\n          return {\n            ...part,\n            value: offsetName,\n          };\n        } else {\n          return part;\n        }\n      });\n    }\n    return parts;\n  }\n\n  resolvedOptions() {\n    return this.dtf.resolvedOptions();\n  }\n}\n\n/**\n * @private\n */\nclass PolyRelFormatter {\n  constructor(intl, isEnglish, opts) {\n    this.opts = { style: \"long\", ...opts };\n    if (!isEnglish && hasRelative()) {\n      this.rtf = getCachedRTF(intl, opts);\n    }\n  }\n\n  format(count, unit) {\n    if (this.rtf) {\n      return this.rtf.format(count, unit);\n    } else {\n      return English.formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== \"long\");\n    }\n  }\n\n  formatToParts(count, unit) {\n    if (this.rtf) {\n      return this.rtf.formatToParts(count, unit);\n    } else {\n      return [];\n    }\n  }\n}\n\n/**\n * @private\n */\n\nexport default class Locale {\n  static fromOpts(opts) {\n    return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);\n  }\n\n  static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {\n    const specifiedLocale = locale || Settings.defaultLocale;\n    // the system locale is useful for human readable strings but annoying for parsing/formatting known formats\n    const localeR = specifiedLocale || (defaultToEN ? \"en-US\" : systemLocale());\n    const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;\n    const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;\n    return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);\n  }\n\n  static resetCache() {\n    sysLocaleCache = null;\n    intlDTCache = {};\n    intlNumCache = {};\n    intlRelCache = {};\n  }\n\n  static fromObject({ locale, numberingSystem, outputCalendar } = {}) {\n    return Locale.create(locale, numberingSystem, outputCalendar);\n  }\n\n  constructor(locale, numbering, outputCalendar, specifiedLocale) {\n    const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);\n\n    this.locale = parsedLocale;\n    this.numberingSystem = numbering || parsedNumberingSystem || null;\n    this.outputCalendar = outputCalendar || parsedOutputCalendar || null;\n    this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);\n\n    this.weekdaysCache = { format: {}, standalone: {} };\n    this.monthsCache = { format: {}, standalone: {} };\n    this.meridiemCache = null;\n    this.eraCache = {};\n\n    this.specifiedLocale = specifiedLocale;\n    this.fastNumbersCached = null;\n  }\n\n  get fastNumbers() {\n    if (this.fastNumbersCached == null) {\n      this.fastNumbersCached = supportsFastNumbers(this);\n    }\n\n    return this.fastNumbersCached;\n  }\n\n  listingMode() {\n    const isActuallyEn = this.isEnglish();\n    const hasNoWeirdness =\n      (this.numberingSystem === null || this.numberingSystem === \"latn\") &&\n      (this.outputCalendar === null || this.outputCalendar === \"gregory\");\n    return isActuallyEn && hasNoWeirdness ? \"en\" : \"intl\";\n  }\n\n  clone(alts) {\n    if (!alts || Object.getOwnPropertyNames(alts).length === 0) {\n      return this;\n    } else {\n      return Locale.create(\n        alts.locale || this.specifiedLocale,\n        alts.numberingSystem || this.numberingSystem,\n        alts.outputCalendar || this.outputCalendar,\n        alts.defaultToEN || false\n      );\n    }\n  }\n\n  redefaultToEN(alts = {}) {\n    return this.clone({ ...alts, defaultToEN: true });\n  }\n\n  redefaultToSystem(alts = {}) {\n    return this.clone({ ...alts, defaultToEN: false });\n  }\n\n  months(length, format = false, defaultOK = true) {\n    return listStuff(this, length, defaultOK, English.months, () => {\n      const intl = format ? { month: length, day: \"numeric\" } : { month: length },\n        formatStr = format ? \"format\" : \"standalone\";\n      if (!this.monthsCache[formatStr][length]) {\n        this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, \"month\"));\n      }\n      return this.monthsCache[formatStr][length];\n    });\n  }\n\n  weekdays(length, format = false, defaultOK = true) {\n    return listStuff(this, length, defaultOK, English.weekdays, () => {\n      const intl = format\n          ? { weekday: length, year: \"numeric\", month: \"long\", day: \"numeric\" }\n          : { weekday: length },\n        formatStr = format ? \"format\" : \"standalone\";\n      if (!this.weekdaysCache[formatStr][length]) {\n        this.weekdaysCache[formatStr][length] = mapWeekdays((dt) =>\n          this.extract(dt, intl, \"weekday\")\n        );\n      }\n      return this.weekdaysCache[formatStr][length];\n    });\n  }\n\n  meridiems(defaultOK = true) {\n    return listStuff(\n      this,\n      undefined,\n      defaultOK,\n      () => English.meridiems,\n      () => {\n        // In theory there could be aribitrary day periods. We're gonna assume there are exactly two\n        // for AM and PM. This is probably wrong, but it's makes parsing way easier.\n        if (!this.meridiemCache) {\n          const intl = { hour: \"numeric\", hourCycle: \"h12\" };\n          this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(\n            (dt) => this.extract(dt, intl, \"dayperiod\")\n          );\n        }\n\n        return this.meridiemCache;\n      }\n    );\n  }\n\n  eras(length, defaultOK = true) {\n    return listStuff(this, length, defaultOK, English.eras, () => {\n      const intl = { era: length };\n\n      // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates\n      // to definitely enumerate them.\n      if (!this.eraCache[length]) {\n        this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) =>\n          this.extract(dt, intl, \"era\")\n        );\n      }\n\n      return this.eraCache[length];\n    });\n  }\n\n  extract(dt, intlOpts, field) {\n    const df = this.dtFormatter(dt, intlOpts),\n      results = df.formatToParts(),\n      matching = results.find((m) => m.type.toLowerCase() === field);\n    return matching ? matching.value : null;\n  }\n\n  numberFormatter(opts = {}) {\n    // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)\n    // (in contrast, the rest of the condition is used heavily)\n    return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);\n  }\n\n  dtFormatter(dt, intlOpts = {}) {\n    return new PolyDateFormatter(dt, this.intl, intlOpts);\n  }\n\n  relFormatter(opts = {}) {\n    return new PolyRelFormatter(this.intl, this.isEnglish(), opts);\n  }\n\n  listFormatter(opts = {}) {\n    return getCachedLF(this.intl, opts);\n  }\n\n  isEnglish() {\n    return (\n      this.locale === \"en\" ||\n      this.locale.toLowerCase() === \"en-us\" ||\n      new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith(\"en-us\")\n    );\n  }\n\n  equals(other) {\n    return (\n      this.locale === other.locale &&\n      this.numberingSystem === other.numberingSystem &&\n      this.outputCalendar === other.outputCalendar\n    );\n  }\n}\n","import * as Formats from \"./formats.js\";\nimport { pick } from \"./util.js\";\n\nfunction stringify(obj) {\n  return JSON.stringify(obj, Object.keys(obj).sort());\n}\n\n/**\n * @private\n */\n\nexport const monthsLong = [\n  \"January\",\n  \"February\",\n  \"March\",\n  \"April\",\n  \"May\",\n  \"June\",\n  \"July\",\n  \"August\",\n  \"September\",\n  \"October\",\n  \"November\",\n  \"December\",\n];\n\nexport const monthsShort = [\n  \"Jan\",\n  \"Feb\",\n  \"Mar\",\n  \"Apr\",\n  \"May\",\n  \"Jun\",\n  \"Jul\",\n  \"Aug\",\n  \"Sep\",\n  \"Oct\",\n  \"Nov\",\n  \"Dec\",\n];\n\nexport const monthsNarrow = [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"];\n\nexport function months(length) {\n  switch (length) {\n    case \"narrow\":\n      return [...monthsNarrow];\n    case \"short\":\n      return [...monthsShort];\n    case \"long\":\n      return [...monthsLong];\n    case \"numeric\":\n      return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"];\n    case \"2-digit\":\n      return [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\"];\n    default:\n      return null;\n  }\n}\n\nexport const weekdaysLong = [\n  \"Monday\",\n  \"Tuesday\",\n  \"Wednesday\",\n  \"Thursday\",\n  \"Friday\",\n  \"Saturday\",\n  \"Sunday\",\n];\n\nexport const weekdaysShort = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\n\nexport const weekdaysNarrow = [\"M\", \"T\", \"W\", \"T\", \"F\", \"S\", \"S\"];\n\nexport function weekdays(length) {\n  switch (length) {\n    case \"narrow\":\n      return [...weekdaysNarrow];\n    case \"short\":\n      return [...weekdaysShort];\n    case \"long\":\n      return [...weekdaysLong];\n    case \"numeric\":\n      return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"];\n    default:\n      return null;\n  }\n}\n\nexport const meridiems = [\"AM\", \"PM\"];\n\nexport const erasLong = [\"Before Christ\", \"Anno Domini\"];\n\nexport const erasShort = [\"BC\", \"AD\"];\n\nexport const erasNarrow = [\"B\", \"A\"];\n\nexport function eras(length) {\n  switch (length) {\n    case \"narrow\":\n      return [...erasNarrow];\n    case \"short\":\n      return [...erasShort];\n    case \"long\":\n      return [...erasLong];\n    default:\n      return null;\n  }\n}\n\nexport function meridiemForDateTime(dt) {\n  return meridiems[dt.hour < 12 ? 0 : 1];\n}\n\nexport function weekdayForDateTime(dt, length) {\n  return weekdays(length)[dt.weekday - 1];\n}\n\nexport function monthForDateTime(dt, length) {\n  return months(length)[dt.month - 1];\n}\n\nexport function eraForDateTime(dt, length) {\n  return eras(length)[dt.year < 0 ? 0 : 1];\n}\n\nexport function formatRelativeTime(unit, count, numeric = \"always\", narrow = false) {\n  const units = {\n    years: [\"year\", \"yr.\"],\n    quarters: [\"quarter\", \"qtr.\"],\n    months: [\"month\", \"mo.\"],\n    weeks: [\"week\", \"wk.\"],\n    days: [\"day\", \"day\", \"days\"],\n    hours: [\"hour\", \"hr.\"],\n    minutes: [\"minute\", \"min.\"],\n    seconds: [\"second\", \"sec.\"],\n  };\n\n  const lastable = [\"hours\", \"minutes\", \"seconds\"].indexOf(unit) === -1;\n\n  if (numeric === \"auto\" && lastable) {\n    const isDay = unit === \"days\";\n    switch (count) {\n      case 1:\n        return isDay ? \"tomorrow\" : `next ${units[unit][0]}`;\n      case -1:\n        return isDay ? \"yesterday\" : `last ${units[unit][0]}`;\n      case 0:\n        return isDay ? \"today\" : `this ${units[unit][0]}`;\n      default: // fall through\n    }\n  }\n\n  const isInPast = Object.is(count, -0) || count < 0,\n    fmtValue = Math.abs(count),\n    singular = fmtValue === 1,\n    lilUnits = units[unit],\n    fmtUnit = narrow\n      ? singular\n        ? lilUnits[1]\n        : lilUnits[2] || lilUnits[1]\n      : singular\n      ? units[unit][0]\n      : unit;\n  return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;\n}\n\nexport function formatString(knownFormat) {\n  // these all have the offsets removed because we don't have access to them\n  // without all the intl stuff this is backfilling\n  const filtered = pick(knownFormat, [\n      \"weekday\",\n      \"era\",\n      \"year\",\n      \"month\",\n      \"day\",\n      \"hour\",\n      \"minute\",\n      \"second\",\n      \"timeZoneName\",\n      \"hourCycle\",\n    ]),\n    key = stringify(filtered),\n    dateTimeHuge = \"EEEE, LLLL d, yyyy, h:mm a\";\n  switch (key) {\n    case stringify(Formats.DATE_SHORT):\n      return \"M/d/yyyy\";\n    case stringify(Formats.DATE_MED):\n      return \"LLL d, yyyy\";\n    case stringify(Formats.DATE_MED_WITH_WEEKDAY):\n      return \"EEE, LLL d, yyyy\";\n    case stringify(Formats.DATE_FULL):\n      return \"LLLL d, yyyy\";\n    case stringify(Formats.DATE_HUGE):\n      return \"EEEE, LLLL d, yyyy\";\n    case stringify(Formats.TIME_SIMPLE):\n      return \"h:mm a\";\n    case stringify(Formats.TIME_WITH_SECONDS):\n      return \"h:mm:ss a\";\n    case stringify(Formats.TIME_WITH_SHORT_OFFSET):\n      return \"h:mm a\";\n    case stringify(Formats.TIME_WITH_LONG_OFFSET):\n      return \"h:mm a\";\n    case stringify(Formats.TIME_24_SIMPLE):\n      return \"HH:mm\";\n    case stringify(Formats.TIME_24_WITH_SECONDS):\n      return \"HH:mm:ss\";\n    case stringify(Formats.TIME_24_WITH_SHORT_OFFSET):\n      return \"HH:mm\";\n    case stringify(Formats.TIME_24_WITH_LONG_OFFSET):\n      return \"HH:mm\";\n    case stringify(Formats.DATETIME_SHORT):\n      return \"M/d/yyyy, h:mm a\";\n    case stringify(Formats.DATETIME_MED):\n      return \"LLL d, yyyy, h:mm a\";\n    case stringify(Formats.DATETIME_FULL):\n      return \"LLLL d, yyyy, h:mm a\";\n    case stringify(Formats.DATETIME_HUGE):\n      return dateTimeHuge;\n    case stringify(Formats.DATETIME_SHORT_WITH_SECONDS):\n      return \"M/d/yyyy, h:mm:ss a\";\n    case stringify(Formats.DATETIME_MED_WITH_SECONDS):\n      return \"LLL d, yyyy, h:mm:ss a\";\n    case stringify(Formats.DATETIME_MED_WITH_WEEKDAY):\n      return \"EEE, d LLL yyyy, h:mm a\";\n    case stringify(Formats.DATETIME_FULL_WITH_SECONDS):\n      return \"LLLL d, yyyy, h:mm:ss a\";\n    case stringify(Formats.DATETIME_HUGE_WITH_SECONDS):\n      return \"EEEE, LLLL d, yyyy, h:mm:ss a\";\n    default:\n      return dateTimeHuge;\n  }\n}\n","import { formatOffset, signedOffset } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * A zone with a fixed offset (meaning no DST)\n * @implements {Zone}\n */\nexport default class FixedOffsetZone extends Zone {\n  /**\n   * Get a singleton instance of UTC\n   * @return {FixedOffsetZone}\n   */\n  static get utcInstance() {\n    if (singleton === null) {\n      singleton = new FixedOffsetZone(0);\n    }\n    return singleton;\n  }\n\n  /**\n   * Get an instance with a specified offset\n   * @param {number} offset - The offset in minutes\n   * @return {FixedOffsetZone}\n   */\n  static instance(offset) {\n    return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);\n  }\n\n  /**\n   * Get an instance of FixedOffsetZone from a UTC offset string, like \"UTC+6\"\n   * @param {string} s - The offset string to parse\n   * @example FixedOffsetZone.parseSpecifier(\"UTC+6\")\n   * @example FixedOffsetZone.parseSpecifier(\"UTC+06\")\n   * @example FixedOffsetZone.parseSpecifier(\"UTC-6:00\")\n   * @return {FixedOffsetZone}\n   */\n  static parseSpecifier(s) {\n    if (s) {\n      const r = s.match(/^utc(?:([+-]\\d{1,2})(?::(\\d{2}))?)?$/i);\n      if (r) {\n        return new FixedOffsetZone(signedOffset(r[1], r[2]));\n      }\n    }\n    return null;\n  }\n\n  constructor(offset) {\n    super();\n    /** @private **/\n    this.fixed = offset;\n  }\n\n  /** @override **/\n  get type() {\n    return \"fixed\";\n  }\n\n  /** @override **/\n  get name() {\n    return this.fixed === 0 ? \"UTC\" : `UTC${formatOffset(this.fixed, \"narrow\")}`;\n  }\n\n  get ianaName() {\n    if (this.fixed === 0) {\n      return \"Etc/UTC\";\n    } else {\n      return `Etc/GMT${formatOffset(-this.fixed, \"narrow\")}`;\n    }\n  }\n\n  /** @override **/\n  offsetName() {\n    return this.name;\n  }\n\n  /** @override **/\n  formatOffset(ts, format) {\n    return formatOffset(this.fixed, format);\n  }\n\n  /** @override **/\n  get isUniversal() {\n    return true;\n  }\n\n  /** @override **/\n  offset() {\n    return this.fixed;\n  }\n\n  /** @override **/\n  equals(otherZone) {\n    return otherZone.type === \"fixed\" && otherZone.fixed === this.fixed;\n  }\n\n  /** @override **/\n  get isValid() {\n    return true;\n  }\n}\n","import Zone from \"../zone.js\";\n\n/**\n * A zone that failed to parse. You should never need to instantiate this.\n * @implements {Zone}\n */\nexport default class InvalidZone extends Zone {\n  constructor(zoneName) {\n    super();\n    /**  @private */\n    this.zoneName = zoneName;\n  }\n\n  /** @override **/\n  get type() {\n    return \"invalid\";\n  }\n\n  /** @override **/\n  get name() {\n    return this.zoneName;\n  }\n\n  /** @override **/\n  get isUniversal() {\n    return false;\n  }\n\n  /** @override **/\n  offsetName() {\n    return null;\n  }\n\n  /** @override **/\n  formatOffset() {\n    return \"\";\n  }\n\n  /** @override **/\n  offset() {\n    return NaN;\n  }\n\n  /** @override **/\n  equals() {\n    return false;\n  }\n\n  /** @override **/\n  get isValid() {\n    return false;\n  }\n}\n","/**\n * @private\n */\n\nimport Zone from \"../zone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport InvalidZone from \"../zones/invalidZone.js\";\n\nimport { isUndefined, isString, isNumber } from \"./util.js\";\nimport SystemZone from \"../zones/systemZone.js\";\n\nexport function normalizeZone(input, defaultZone) {\n  let offset;\n  if (isUndefined(input) || input === null) {\n    return defaultZone;\n  } else if (input instanceof Zone) {\n    return input;\n  } else if (isString(input)) {\n    const lowered = input.toLowerCase();\n    if (lowered === \"default\") return defaultZone;\n    else if (lowered === \"local\" || lowered === \"system\") return SystemZone.instance;\n    else if (lowered === \"utc\" || lowered === \"gmt\") return FixedOffsetZone.utcInstance;\n    else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);\n  } else if (isNumber(input)) {\n    return FixedOffsetZone.instance(input);\n  } else if (typeof input === \"object\" && input.offset && typeof input.offset === \"number\") {\n    // This is dumb, but the instanceof check above doesn't seem to really work\n    // so we're duck checking it\n    return input;\n  } else {\n    return new InvalidZone(input);\n  }\n}\n","/*\n  This is just a junk drawer, containing anything used across multiple classes.\n  Because Luxon is small(ish), this should stay small and we won't worry about splitting\n  it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area.\n*/\n\nimport { InvalidArgumentError } from \"../errors.js\";\nimport Settings from \"../settings.js\";\n\n/**\n * @private\n */\n\n// TYPES\n\nexport function isUndefined(o) {\n  return typeof o === \"undefined\";\n}\n\nexport function isNumber(o) {\n  return typeof o === \"number\";\n}\n\nexport function isInteger(o) {\n  return typeof o === \"number\" && o % 1 === 0;\n}\n\nexport function isString(o) {\n  return typeof o === \"string\";\n}\n\nexport function isDate(o) {\n  return Object.prototype.toString.call(o) === \"[object Date]\";\n}\n\n// CAPABILITIES\n\nexport function hasRelative() {\n  try {\n    return typeof Intl !== \"undefined\" && !!Intl.RelativeTimeFormat;\n  } catch (e) {\n    return false;\n  }\n}\n\n// OBJECTS AND ARRAYS\n\nexport function maybeArray(thing) {\n  return Array.isArray(thing) ? thing : [thing];\n}\n\nexport function bestBy(arr, by, compare) {\n  if (arr.length === 0) {\n    return undefined;\n  }\n  return arr.reduce((best, next) => {\n    const pair = [by(next), next];\n    if (!best) {\n      return pair;\n    } else if (compare(best[0], pair[0]) === best[0]) {\n      return best;\n    } else {\n      return pair;\n    }\n  }, null)[1];\n}\n\nexport function pick(obj, keys) {\n  return keys.reduce((a, k) => {\n    a[k] = obj[k];\n    return a;\n  }, {});\n}\n\nexport function hasOwnProperty(obj, prop) {\n  return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n// NUMBERS AND STRINGS\n\nexport function integerBetween(thing, bottom, top) {\n  return isInteger(thing) && thing >= bottom && thing <= top;\n}\n\n// x % n but takes the sign of n instead of x\nexport function floorMod(x, n) {\n  return x - n * Math.floor(x / n);\n}\n\nexport function padStart(input, n = 2) {\n  const isNeg = input < 0;\n  let padded;\n  if (isNeg) {\n    padded = \"-\" + (\"\" + -input).padStart(n, \"0\");\n  } else {\n    padded = (\"\" + input).padStart(n, \"0\");\n  }\n  return padded;\n}\n\nexport function parseInteger(string) {\n  if (isUndefined(string) || string === null || string === \"\") {\n    return undefined;\n  } else {\n    return parseInt(string, 10);\n  }\n}\n\nexport function parseFloating(string) {\n  if (isUndefined(string) || string === null || string === \"\") {\n    return undefined;\n  } else {\n    return parseFloat(string);\n  }\n}\n\nexport function parseMillis(fraction) {\n  // Return undefined (instead of 0) in these cases, where fraction is not set\n  if (isUndefined(fraction) || fraction === null || fraction === \"\") {\n    return undefined;\n  } else {\n    const f = parseFloat(\"0.\" + fraction) * 1000;\n    return Math.floor(f);\n  }\n}\n\nexport function roundTo(number, digits, towardZero = false) {\n  const factor = 10 ** digits,\n    rounder = towardZero ? Math.trunc : Math.round;\n  return rounder(number * factor) / factor;\n}\n\n// DATE BASICS\n\nexport function isLeapYear(year) {\n  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nexport function daysInYear(year) {\n  return isLeapYear(year) ? 366 : 365;\n}\n\nexport function daysInMonth(year, month) {\n  const modMonth = floorMod(month - 1, 12) + 1,\n    modYear = year + (month - modMonth) / 12;\n\n  if (modMonth === 2) {\n    return isLeapYear(modYear) ? 29 : 28;\n  } else {\n    return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];\n  }\n}\n\n// covert a calendar object to a local timestamp (epoch, but with the offset baked in)\nexport function objToLocalTS(obj) {\n  let d = Date.UTC(\n    obj.year,\n    obj.month - 1,\n    obj.day,\n    obj.hour,\n    obj.minute,\n    obj.second,\n    obj.millisecond\n  );\n\n  // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that\n  if (obj.year < 100 && obj.year >= 0) {\n    d = new Date(d);\n    // set the month and day again, this is necessary because year 2000 is a leap year, but year 100 is not\n    // so if obj.year is in 99, but obj.day makes it roll over into year 100,\n    // the calculations done by Date.UTC are using year 2000 - which is incorrect\n    d.setUTCFullYear(obj.year, obj.month - 1, obj.day);\n  }\n  return +d;\n}\n\nexport function weeksInWeekYear(weekYear) {\n  const p1 =\n      (weekYear +\n        Math.floor(weekYear / 4) -\n        Math.floor(weekYear / 100) +\n        Math.floor(weekYear / 400)) %\n      7,\n    last = weekYear - 1,\n    p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;\n  return p1 === 4 || p2 === 3 ? 53 : 52;\n}\n\nexport function untruncateYear(year) {\n  if (year > 99) {\n    return year;\n  } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2000 + year;\n}\n\n// PARSING\n\nexport function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {\n  const date = new Date(ts),\n    intlOpts = {\n      hourCycle: \"h23\",\n      year: \"numeric\",\n      month: \"2-digit\",\n      day: \"2-digit\",\n      hour: \"2-digit\",\n      minute: \"2-digit\",\n    };\n\n  if (timeZone) {\n    intlOpts.timeZone = timeZone;\n  }\n\n  const modified = { timeZoneName: offsetFormat, ...intlOpts };\n\n  const parsed = new Intl.DateTimeFormat(locale, modified)\n    .formatToParts(date)\n    .find((m) => m.type.toLowerCase() === \"timezonename\");\n  return parsed ? parsed.value : null;\n}\n\n// signedOffset('-5', '30') -> -330\nexport function signedOffset(offHourStr, offMinuteStr) {\n  let offHour = parseInt(offHourStr, 10);\n\n  // don't || this because we want to preserve -0\n  if (Number.isNaN(offHour)) {\n    offHour = 0;\n  }\n\n  const offMin = parseInt(offMinuteStr, 10) || 0,\n    offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;\n  return offHour * 60 + offMinSigned;\n}\n\n// COERCION\n\nexport function asNumber(value) {\n  const numericValue = Number(value);\n  if (typeof value === \"boolean\" || value === \"\" || Number.isNaN(numericValue))\n    throw new InvalidArgumentError(`Invalid unit value ${value}`);\n  return numericValue;\n}\n\nexport function normalizeObject(obj, normalizer) {\n  const normalized = {};\n  for (const u in obj) {\n    if (hasOwnProperty(obj, u)) {\n      const v = obj[u];\n      if (v === undefined || v === null) continue;\n      normalized[normalizer(u)] = asNumber(v);\n    }\n  }\n  return normalized;\n}\n\nexport function formatOffset(offset, format) {\n  const hours = Math.trunc(Math.abs(offset / 60)),\n    minutes = Math.trunc(Math.abs(offset % 60)),\n    sign = offset >= 0 ? \"+\" : \"-\";\n\n  switch (format) {\n    case \"short\":\n      return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;\n    case \"narrow\":\n      return `${sign}${hours}${minutes > 0 ? `:${minutes}` : \"\"}`;\n    case \"techie\":\n      return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;\n    default:\n      throw new RangeError(`Value format ${format} is out of range for property format`);\n  }\n}\n\nexport function timeObject(obj) {\n  return pick(obj, [\"hour\", \"minute\", \"second\", \"millisecond\"]);\n}\n","import SystemZone from \"./zones/systemZone.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport Locale from \"./impl/locale.js\";\n\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\n\nlet now = () => Date.now(),\n  defaultZone = \"system\",\n  defaultLocale = null,\n  defaultNumberingSystem = null,\n  defaultOutputCalendar = null,\n  twoDigitCutoffYear = 60,\n  throwOnInvalid;\n\n/**\n * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.\n */\nexport default class Settings {\n  /**\n   * Get the callback for returning the current timestamp.\n   * @type {function}\n   */\n  static get now() {\n    return now;\n  }\n\n  /**\n   * Set the callback for returning the current timestamp.\n   * The function should return a number, which will be interpreted as an Epoch millisecond count\n   * @type {function}\n   * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future\n   * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time\n   */\n  static set now(n) {\n    now = n;\n  }\n\n  /**\n   * Set the default time zone to create DateTimes in. Does not affect existing instances.\n   * Use the value \"system\" to reset this value to the system's time zone.\n   * @type {string}\n   */\n  static set defaultZone(zone) {\n    defaultZone = zone;\n  }\n\n  /**\n   * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.\n   * The default value is the system's time zone (the one set on the machine that runs this code).\n   * @type {Zone}\n   */\n  static get defaultZone() {\n    return normalizeZone(defaultZone, SystemZone.instance);\n  }\n\n  /**\n   * Get the default locale to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static get defaultLocale() {\n    return defaultLocale;\n  }\n\n  /**\n   * Set the default locale to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static set defaultLocale(locale) {\n    defaultLocale = locale;\n  }\n\n  /**\n   * Get the default numbering system to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static get defaultNumberingSystem() {\n    return defaultNumberingSystem;\n  }\n\n  /**\n   * Set the default numbering system to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static set defaultNumberingSystem(numberingSystem) {\n    defaultNumberingSystem = numberingSystem;\n  }\n\n  /**\n   * Get the default output calendar to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static get defaultOutputCalendar() {\n    return defaultOutputCalendar;\n  }\n\n  /**\n   * Set the default output calendar to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static set defaultOutputCalendar(outputCalendar) {\n    defaultOutputCalendar = outputCalendar;\n  }\n\n  /**\n   * Get the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century.\n   * @type {number}\n   */\n  static get twoDigitCutoffYear() {\n    return twoDigitCutoffYear;\n  }\n\n  /**\n   * Set the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century.\n   * @type {number}\n   * @example Settings.twoDigitCutoffYear = 0 // cut-off year is 0, so all 'yy' are interpretted as current century\n   * @example Settings.twoDigitCutoffYear = 50 // '49' -> 1949; '50' -> 2050\n   * @example Settings.twoDigitCutoffYear = 1950 // interpretted as 50\n   * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpretted as 50\n   */\n  static set twoDigitCutoffYear(cutoffYear) {\n    twoDigitCutoffYear = cutoffYear % 100;\n  }\n\n  /**\n   * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n   * @type {boolean}\n   */\n  static get throwOnInvalid() {\n    return throwOnInvalid;\n  }\n\n  /**\n   * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n   * @type {boolean}\n   */\n  static set throwOnInvalid(t) {\n    throwOnInvalid = t;\n  }\n\n  /**\n   * Reset Luxon's global caches. Should only be necessary in testing scenarios.\n   * @return {void}\n   */\n  static resetCaches() {\n    Locale.resetCache();\n    IANAZone.resetCache();\n  }\n}\n","import * as English from \"./english.js\";\nimport * as Formats from \"./formats.js\";\nimport { padStart } from \"./util.js\";\n\nfunction stringifyTokens(splits, tokenToString) {\n  let s = \"\";\n  for (const token of splits) {\n    if (token.literal) {\n      s += token.val;\n    } else {\n      s += tokenToString(token.val);\n    }\n  }\n  return s;\n}\n\nconst macroTokenToFormatOpts = {\n  D: Formats.DATE_SHORT,\n  DD: Formats.DATE_MED,\n  DDD: Formats.DATE_FULL,\n  DDDD: Formats.DATE_HUGE,\n  t: Formats.TIME_SIMPLE,\n  tt: Formats.TIME_WITH_SECONDS,\n  ttt: Formats.TIME_WITH_SHORT_OFFSET,\n  tttt: Formats.TIME_WITH_LONG_OFFSET,\n  T: Formats.TIME_24_SIMPLE,\n  TT: Formats.TIME_24_WITH_SECONDS,\n  TTT: Formats.TIME_24_WITH_SHORT_OFFSET,\n  TTTT: Formats.TIME_24_WITH_LONG_OFFSET,\n  f: Formats.DATETIME_SHORT,\n  ff: Formats.DATETIME_MED,\n  fff: Formats.DATETIME_FULL,\n  ffff: Formats.DATETIME_HUGE,\n  F: Formats.DATETIME_SHORT_WITH_SECONDS,\n  FF: Formats.DATETIME_MED_WITH_SECONDS,\n  FFF: Formats.DATETIME_FULL_WITH_SECONDS,\n  FFFF: Formats.DATETIME_HUGE_WITH_SECONDS,\n};\n\n/**\n * @private\n */\n\nexport default class Formatter {\n  static create(locale, opts = {}) {\n    return new Formatter(locale, opts);\n  }\n\n  static parseFormat(fmt) {\n    // white-space is always considered a literal in user-provided formats\n    // the \" \" token has a special meaning (see unitForToken)\n\n    let current = null,\n      currentFull = \"\",\n      bracketed = false;\n    const splits = [];\n    for (let i = 0; i < fmt.length; i++) {\n      const c = fmt.charAt(i);\n      if (c === \"'\") {\n        if (currentFull.length > 0) {\n          splits.push({ literal: bracketed || /^\\s+$/.test(currentFull), val: currentFull });\n        }\n        current = null;\n        currentFull = \"\";\n        bracketed = !bracketed;\n      } else if (bracketed) {\n        currentFull += c;\n      } else if (c === current) {\n        currentFull += c;\n      } else {\n        if (currentFull.length > 0) {\n          splits.push({ literal: /^\\s+$/.test(currentFull), val: currentFull });\n        }\n        currentFull = c;\n        current = c;\n      }\n    }\n\n    if (currentFull.length > 0) {\n      splits.push({ literal: bracketed || /^\\s+$/.test(currentFull), val: currentFull });\n    }\n\n    return splits;\n  }\n\n  static macroTokenToFormatOpts(token) {\n    return macroTokenToFormatOpts[token];\n  }\n\n  constructor(locale, formatOpts) {\n    this.opts = formatOpts;\n    this.loc = locale;\n    this.systemLoc = null;\n  }\n\n  formatWithSystemDefault(dt, opts) {\n    if (this.systemLoc === null) {\n      this.systemLoc = this.loc.redefaultToSystem();\n    }\n    const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts });\n    return df.format();\n  }\n\n  formatDateTime(dt, opts = {}) {\n    const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n    return df.format();\n  }\n\n  formatDateTimeParts(dt, opts = {}) {\n    const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n    return df.formatToParts();\n  }\n\n  formatInterval(interval, opts = {}) {\n    const df = this.loc.dtFormatter(interval.start, { ...this.opts, ...opts });\n    return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate());\n  }\n\n  resolvedOptions(dt, opts = {}) {\n    const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n    return df.resolvedOptions();\n  }\n\n  num(n, p = 0) {\n    // we get some perf out of doing this here, annoyingly\n    if (this.opts.forceSimple) {\n      return padStart(n, p);\n    }\n\n    const opts = { ...this.opts };\n\n    if (p > 0) {\n      opts.padTo = p;\n    }\n\n    return this.loc.numberFormatter(opts).format(n);\n  }\n\n  formatDateTimeFromString(dt, fmt) {\n    const knownEnglish = this.loc.listingMode() === \"en\",\n      useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== \"gregory\",\n      string = (opts, extract) => this.loc.extract(dt, opts, extract),\n      formatOffset = (opts) => {\n        if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {\n          return \"Z\";\n        }\n\n        return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : \"\";\n      },\n      meridiem = () =>\n        knownEnglish\n          ? English.meridiemForDateTime(dt)\n          : string({ hour: \"numeric\", hourCycle: \"h12\" }, \"dayperiod\"),\n      month = (length, standalone) =>\n        knownEnglish\n          ? English.monthForDateTime(dt, length)\n          : string(standalone ? { month: length } : { month: length, day: \"numeric\" }, \"month\"),\n      weekday = (length, standalone) =>\n        knownEnglish\n          ? English.weekdayForDateTime(dt, length)\n          : string(\n              standalone ? { weekday: length } : { weekday: length, month: \"long\", day: \"numeric\" },\n              \"weekday\"\n            ),\n      maybeMacro = (token) => {\n        const formatOpts = Formatter.macroTokenToFormatOpts(token);\n        if (formatOpts) {\n          return this.formatWithSystemDefault(dt, formatOpts);\n        } else {\n          return token;\n        }\n      },\n      era = (length) =>\n        knownEnglish ? English.eraForDateTime(dt, length) : string({ era: length }, \"era\"),\n      tokenToString = (token) => {\n        // Where possible: http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles\n        switch (token) {\n          // ms\n          case \"S\":\n            return this.num(dt.millisecond);\n          case \"u\":\n          // falls through\n          case \"SSS\":\n            return this.num(dt.millisecond, 3);\n          // seconds\n          case \"s\":\n            return this.num(dt.second);\n          case \"ss\":\n            return this.num(dt.second, 2);\n          // fractional seconds\n          case \"uu\":\n            return this.num(Math.floor(dt.millisecond / 10), 2);\n          case \"uuu\":\n            return this.num(Math.floor(dt.millisecond / 100));\n          // minutes\n          case \"m\":\n            return this.num(dt.minute);\n          case \"mm\":\n            return this.num(dt.minute, 2);\n          // hours\n          case \"h\":\n            return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);\n          case \"hh\":\n            return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);\n          case \"H\":\n            return this.num(dt.hour);\n          case \"HH\":\n            return this.num(dt.hour, 2);\n          // offset\n          case \"Z\":\n            // like +6\n            return formatOffset({ format: \"narrow\", allowZ: this.opts.allowZ });\n          case \"ZZ\":\n            // like +06:00\n            return formatOffset({ format: \"short\", allowZ: this.opts.allowZ });\n          case \"ZZZ\":\n            // like +0600\n            return formatOffset({ format: \"techie\", allowZ: this.opts.allowZ });\n          case \"ZZZZ\":\n            // like EST\n            return dt.zone.offsetName(dt.ts, { format: \"short\", locale: this.loc.locale });\n          case \"ZZZZZ\":\n            // like Eastern Standard Time\n            return dt.zone.offsetName(dt.ts, { format: \"long\", locale: this.loc.locale });\n          // zone\n          case \"z\":\n            // like America/New_York\n            return dt.zoneName;\n          // meridiems\n          case \"a\":\n            return meridiem();\n          // dates\n          case \"d\":\n            return useDateTimeFormatter ? string({ day: \"numeric\" }, \"day\") : this.num(dt.day);\n          case \"dd\":\n            return useDateTimeFormatter ? string({ day: \"2-digit\" }, \"day\") : this.num(dt.day, 2);\n          // weekdays - standalone\n          case \"c\":\n            // like 1\n            return this.num(dt.weekday);\n          case \"ccc\":\n            // like 'Tues'\n            return weekday(\"short\", true);\n          case \"cccc\":\n            // like 'Tuesday'\n            return weekday(\"long\", true);\n          case \"ccccc\":\n            // like 'T'\n            return weekday(\"narrow\", true);\n          // weekdays - format\n          case \"E\":\n            // like 1\n            return this.num(dt.weekday);\n          case \"EEE\":\n            // like 'Tues'\n            return weekday(\"short\", false);\n          case \"EEEE\":\n            // like 'Tuesday'\n            return weekday(\"long\", false);\n          case \"EEEEE\":\n            // like 'T'\n            return weekday(\"narrow\", false);\n          // months - standalone\n          case \"L\":\n            // like 1\n            return useDateTimeFormatter\n              ? string({ month: \"numeric\", day: \"numeric\" }, \"month\")\n              : this.num(dt.month);\n          case \"LL\":\n            // like 01, doesn't seem to work\n            return useDateTimeFormatter\n              ? string({ month: \"2-digit\", day: \"numeric\" }, \"month\")\n              : this.num(dt.month, 2);\n          case \"LLL\":\n            // like Jan\n            return month(\"short\", true);\n          case \"LLLL\":\n            // like January\n            return month(\"long\", true);\n          case \"LLLLL\":\n            // like J\n            return month(\"narrow\", true);\n          // months - format\n          case \"M\":\n            // like 1\n            return useDateTimeFormatter\n              ? string({ month: \"numeric\" }, \"month\")\n              : this.num(dt.month);\n          case \"MM\":\n            // like 01\n            return useDateTimeFormatter\n              ? string({ month: \"2-digit\" }, \"month\")\n              : this.num(dt.month, 2);\n          case \"MMM\":\n            // like Jan\n            return month(\"short\", false);\n          case \"MMMM\":\n            // like January\n            return month(\"long\", false);\n          case \"MMMMM\":\n            // like J\n            return month(\"narrow\", false);\n          // years\n          case \"y\":\n            // like 2014\n            return useDateTimeFormatter ? string({ year: \"numeric\" }, \"year\") : this.num(dt.year);\n          case \"yy\":\n            // like 14\n            return useDateTimeFormatter\n              ? string({ year: \"2-digit\" }, \"year\")\n              : this.num(dt.year.toString().slice(-2), 2);\n          case \"yyyy\":\n            // like 0012\n            return useDateTimeFormatter\n              ? string({ year: \"numeric\" }, \"year\")\n              : this.num(dt.year, 4);\n          case \"yyyyyy\":\n            // like 000012\n            return useDateTimeFormatter\n              ? string({ year: \"numeric\" }, \"year\")\n              : this.num(dt.year, 6);\n          // eras\n          case \"G\":\n            // like AD\n            return era(\"short\");\n          case \"GG\":\n            // like Anno Domini\n            return era(\"long\");\n          case \"GGGGG\":\n            return era(\"narrow\");\n          case \"kk\":\n            return this.num(dt.weekYear.toString().slice(-2), 2);\n          case \"kkkk\":\n            return this.num(dt.weekYear, 4);\n          case \"W\":\n            return this.num(dt.weekNumber);\n          case \"WW\":\n            return this.num(dt.weekNumber, 2);\n          case \"o\":\n            return this.num(dt.ordinal);\n          case \"ooo\":\n            return this.num(dt.ordinal, 3);\n          case \"q\":\n            // like 1\n            return this.num(dt.quarter);\n          case \"qq\":\n            // like 01\n            return this.num(dt.quarter, 2);\n          case \"X\":\n            return this.num(Math.floor(dt.ts / 1000));\n          case \"x\":\n            return this.num(dt.ts);\n          default:\n            return maybeMacro(token);\n        }\n      };\n\n    return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);\n  }\n\n  formatDurationFromString(dur, fmt) {\n    const tokenToField = (token) => {\n        switch (token[0]) {\n          case \"S\":\n            return \"millisecond\";\n          case \"s\":\n            return \"second\";\n          case \"m\":\n            return \"minute\";\n          case \"h\":\n            return \"hour\";\n          case \"d\":\n            return \"day\";\n          case \"w\":\n            return \"week\";\n          case \"M\":\n            return \"month\";\n          case \"y\":\n            return \"year\";\n          default:\n            return null;\n        }\n      },\n      tokenToString = (lildur) => (token) => {\n        const mapped = tokenToField(token);\n        if (mapped) {\n          return this.num(lildur.get(mapped), token.length);\n        } else {\n          return token;\n        }\n      },\n      tokens = Formatter.parseFormat(fmt),\n      realTokens = tokens.reduce(\n        (found, { literal, val }) => (literal ? found : found.concat(val)),\n        []\n      ),\n      collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t));\n    return stringifyTokens(tokens, tokenToString(collapsed));\n  }\n}\n","export default class Invalid {\n  constructor(reason, explanation) {\n    this.reason = reason;\n    this.explanation = explanation;\n  }\n\n  toMessage() {\n    if (this.explanation) {\n      return `${this.reason}: ${this.explanation}`;\n    } else {\n      return this.reason;\n    }\n  }\n}\n","import {\n  untruncateYear,\n  signedOffset,\n  parseInteger,\n  parseMillis,\n  isUndefined,\n  parseFloating,\n} from \"./util.js\";\nimport * as English from \"./english.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n/*\n * This file handles parsing for well-specified formats. Here's how it works:\n * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.\n * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object\n * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.\n * Extractors can take a \"cursor\" representing the offset in the match to look at. This makes it easy to combine extractors.\n * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.\n * Some extractions are super dumb and simpleParse and fromStrings help DRY them.\n */\n\nconst ianaRegex = /[A-Za-z_+-]{1,256}(?::?\\/[A-Za-z0-9_+-]{1,256}(?:\\/[A-Za-z0-9_+-]{1,256})?)?/;\n\nfunction combineRegexes(...regexes) {\n  const full = regexes.reduce((f, r) => f + r.source, \"\");\n  return RegExp(`^${full}$`);\n}\n\nfunction combineExtractors(...extractors) {\n  return (m) =>\n    extractors\n      .reduce(\n        ([mergedVals, mergedZone, cursor], ex) => {\n          const [val, zone, next] = ex(m, cursor);\n          return [{ ...mergedVals, ...val }, zone || mergedZone, next];\n        },\n        [{}, null, 1]\n      )\n      .slice(0, 2);\n}\n\nfunction parse(s, ...patterns) {\n  if (s == null) {\n    return [null, null];\n  }\n\n  for (const [regex, extractor] of patterns) {\n    const m = regex.exec(s);\n    if (m) {\n      return extractor(m);\n    }\n  }\n  return [null, null];\n}\n\nfunction simpleParse(...keys) {\n  return (match, cursor) => {\n    const ret = {};\n    let i;\n\n    for (i = 0; i < keys.length; i++) {\n      ret[keys[i]] = parseInteger(match[cursor + i]);\n    }\n    return [ret, null, cursor + i];\n  };\n}\n\n// ISO and SQL parsing\nconst offsetRegex = /(?:(Z)|([+-]\\d\\d)(?::?(\\d\\d))?)/;\nconst isoExtendedZone = `(?:${offsetRegex.source}?(?:\\\\[(${ianaRegex.source})\\\\])?)?`;\nconst isoTimeBaseRegex = /(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:[.,](\\d{1,30}))?)?)?/;\nconst isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);\nconst isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`);\nconst isoYmdRegex = /([+-]\\d{6}|\\d{4})(?:-?(\\d\\d)(?:-?(\\d\\d))?)?/;\nconst isoWeekRegex = /(\\d{4})-?W(\\d\\d)(?:-?(\\d))?/;\nconst isoOrdinalRegex = /(\\d{4})-?(\\d{3})/;\nconst extractISOWeekData = simpleParse(\"weekYear\", \"weekNumber\", \"weekDay\");\nconst extractISOOrdinalData = simpleParse(\"year\", \"ordinal\");\nconst sqlYmdRegex = /(\\d{4})-(\\d\\d)-(\\d\\d)/; // dumbed-down version of the ISO one\nconst sqlTimeRegex = RegExp(\n  `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`\n);\nconst sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);\n\nfunction int(match, pos, fallback) {\n  const m = match[pos];\n  return isUndefined(m) ? fallback : parseInteger(m);\n}\n\nfunction extractISOYmd(match, cursor) {\n  const item = {\n    year: int(match, cursor),\n    month: int(match, cursor + 1, 1),\n    day: int(match, cursor + 2, 1),\n  };\n\n  return [item, null, cursor + 3];\n}\n\nfunction extractISOTime(match, cursor) {\n  const item = {\n    hours: int(match, cursor, 0),\n    minutes: int(match, cursor + 1, 0),\n    seconds: int(match, cursor + 2, 0),\n    milliseconds: parseMillis(match[cursor + 3]),\n  };\n\n  return [item, null, cursor + 4];\n}\n\nfunction extractISOOffset(match, cursor) {\n  const local = !match[cursor] && !match[cursor + 1],\n    fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),\n    zone = local ? null : FixedOffsetZone.instance(fullOffset);\n  return [{}, zone, cursor + 3];\n}\n\nfunction extractIANAZone(match, cursor) {\n  const zone = match[cursor] ? IANAZone.create(match[cursor]) : null;\n  return [{}, zone, cursor + 1];\n}\n\n// ISO time parsing\n\nconst isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);\n\n// ISO duration parsing\n\nconst isoDuration =\n  /^-?P(?:(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)Y)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)W)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)D)?(?:T(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)H)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20})(?:[.,](-?\\d{1,20}))?S)?)?)$/;\n\nfunction extractISODuration(match) {\n  const [s, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] =\n    match;\n\n  const hasNegativePrefix = s[0] === \"-\";\n  const negativeSeconds = secondStr && secondStr[0] === \"-\";\n\n  const maybeNegate = (num, force = false) =>\n    num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num;\n\n  return [\n    {\n      years: maybeNegate(parseFloating(yearStr)),\n      months: maybeNegate(parseFloating(monthStr)),\n      weeks: maybeNegate(parseFloating(weekStr)),\n      days: maybeNegate(parseFloating(dayStr)),\n      hours: maybeNegate(parseFloating(hourStr)),\n      minutes: maybeNegate(parseFloating(minuteStr)),\n      seconds: maybeNegate(parseFloating(secondStr), secondStr === \"-0\"),\n      milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds),\n    },\n  ];\n}\n\n// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York\n// and not just that we're in -240 *right now*. But since I don't think these are used that often\n// I'm just going to ignore that\nconst obsOffsets = {\n  GMT: 0,\n  EDT: -4 * 60,\n  EST: -5 * 60,\n  CDT: -5 * 60,\n  CST: -6 * 60,\n  MDT: -6 * 60,\n  MST: -7 * 60,\n  PDT: -7 * 60,\n  PST: -8 * 60,\n};\n\nfunction fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {\n  const result = {\n    year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),\n    month: English.monthsShort.indexOf(monthStr) + 1,\n    day: parseInteger(dayStr),\n    hour: parseInteger(hourStr),\n    minute: parseInteger(minuteStr),\n  };\n\n  if (secondStr) result.second = parseInteger(secondStr);\n  if (weekdayStr) {\n    result.weekday =\n      weekdayStr.length > 3\n        ? English.weekdaysLong.indexOf(weekdayStr) + 1\n        : English.weekdaysShort.indexOf(weekdayStr) + 1;\n  }\n\n  return result;\n}\n\n// RFC 2822/5322\nconst rfc2822 =\n  /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\\d\\d)(\\d\\d)))$/;\n\nfunction extractRFC2822(match) {\n  const [\n      ,\n      weekdayStr,\n      dayStr,\n      monthStr,\n      yearStr,\n      hourStr,\n      minuteStr,\n      secondStr,\n      obsOffset,\n      milOffset,\n      offHourStr,\n      offMinuteStr,\n    ] = match,\n    result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n\n  let offset;\n  if (obsOffset) {\n    offset = obsOffsets[obsOffset];\n  } else if (milOffset) {\n    offset = 0;\n  } else {\n    offset = signedOffset(offHourStr, offMinuteStr);\n  }\n\n  return [result, new FixedOffsetZone(offset)];\n}\n\nfunction preprocessRFC2822(s) {\n  // Remove comments and folding whitespace and replace multiple-spaces with a single space\n  return s\n    .replace(/\\([^()]*\\)|[\\n\\t]/g, \" \")\n    .replace(/(\\s\\s+)/g, \" \")\n    .trim();\n}\n\n// http date\n\nconst rfc1123 =\n    /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d\\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\\d{4}) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n  rfc850 =\n    /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d\\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n  ascii =\n    /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \\d|\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) (\\d{4})$/;\n\nfunction extractRFC1123Or850(match) {\n  const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match,\n    result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n  return [result, FixedOffsetZone.utcInstance];\n}\n\nfunction extractASCII(match) {\n  const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match,\n    result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n  return [result, FixedOffsetZone.utcInstance];\n}\n\nconst isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);\nconst isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);\nconst isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);\nconst isoTimeCombinedRegex = combineRegexes(isoTimeRegex);\n\nconst extractISOYmdTimeAndOffset = combineExtractors(\n  extractISOYmd,\n  extractISOTime,\n  extractISOOffset,\n  extractIANAZone\n);\nconst extractISOWeekTimeAndOffset = combineExtractors(\n  extractISOWeekData,\n  extractISOTime,\n  extractISOOffset,\n  extractIANAZone\n);\nconst extractISOOrdinalDateAndTime = combineExtractors(\n  extractISOOrdinalData,\n  extractISOTime,\n  extractISOOffset,\n  extractIANAZone\n);\nconst extractISOTimeAndOffset = combineExtractors(\n  extractISOTime,\n  extractISOOffset,\n  extractIANAZone\n);\n\n/*\n * @private\n */\n\nexport function parseISODate(s) {\n  return parse(\n    s,\n    [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n    [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset],\n    [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime],\n    [isoTimeCombinedRegex, extractISOTimeAndOffset]\n  );\n}\n\nexport function parseRFC2822Date(s) {\n  return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);\n}\n\nexport function parseHTTPDate(s) {\n  return parse(\n    s,\n    [rfc1123, extractRFC1123Or850],\n    [rfc850, extractRFC1123Or850],\n    [ascii, extractASCII]\n  );\n}\n\nexport function parseISODuration(s) {\n  return parse(s, [isoDuration, extractISODuration]);\n}\n\nconst extractISOTimeOnly = combineExtractors(extractISOTime);\n\nexport function parseISOTimeOnly(s) {\n  return parse(s, [isoTimeOnly, extractISOTimeOnly]);\n}\n\nconst sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);\nconst sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);\n\nconst extractISOTimeOffsetAndIANAZone = combineExtractors(\n  extractISOTime,\n  extractISOOffset,\n  extractIANAZone\n);\n\nexport function parseSQL(s) {\n  return parse(\n    s,\n    [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n    [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]\n  );\n}\n","import { InvalidArgumentError, InvalidDurationError, InvalidUnitError } from \"./errors.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport Invalid from \"./impl/invalid.js\";\nimport Locale from \"./impl/locale.js\";\nimport { parseISODuration, parseISOTimeOnly } from \"./impl/regexParser.js\";\nimport {\n  asNumber,\n  hasOwnProperty,\n  isNumber,\n  isUndefined,\n  normalizeObject,\n  roundTo,\n} from \"./impl/util.js\";\nimport Settings from \"./settings.js\";\n\nconst INVALID = \"Invalid Duration\";\n\n// unit conversion constants\nexport const lowOrderMatrix = {\n    weeks: {\n      days: 7,\n      hours: 7 * 24,\n      minutes: 7 * 24 * 60,\n      seconds: 7 * 24 * 60 * 60,\n      milliseconds: 7 * 24 * 60 * 60 * 1000,\n    },\n    days: {\n      hours: 24,\n      minutes: 24 * 60,\n      seconds: 24 * 60 * 60,\n      milliseconds: 24 * 60 * 60 * 1000,\n    },\n    hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 },\n    minutes: { seconds: 60, milliseconds: 60 * 1000 },\n    seconds: { milliseconds: 1000 },\n  },\n  casualMatrix = {\n    years: {\n      quarters: 4,\n      months: 12,\n      weeks: 52,\n      days: 365,\n      hours: 365 * 24,\n      minutes: 365 * 24 * 60,\n      seconds: 365 * 24 * 60 * 60,\n      milliseconds: 365 * 24 * 60 * 60 * 1000,\n    },\n    quarters: {\n      months: 3,\n      weeks: 13,\n      days: 91,\n      hours: 91 * 24,\n      minutes: 91 * 24 * 60,\n      seconds: 91 * 24 * 60 * 60,\n      milliseconds: 91 * 24 * 60 * 60 * 1000,\n    },\n    months: {\n      weeks: 4,\n      days: 30,\n      hours: 30 * 24,\n      minutes: 30 * 24 * 60,\n      seconds: 30 * 24 * 60 * 60,\n      milliseconds: 30 * 24 * 60 * 60 * 1000,\n    },\n\n    ...lowOrderMatrix,\n  },\n  daysInYearAccurate = 146097.0 / 400,\n  daysInMonthAccurate = 146097.0 / 4800,\n  accurateMatrix = {\n    years: {\n      quarters: 4,\n      months: 12,\n      weeks: daysInYearAccurate / 7,\n      days: daysInYearAccurate,\n      hours: daysInYearAccurate * 24,\n      minutes: daysInYearAccurate * 24 * 60,\n      seconds: daysInYearAccurate * 24 * 60 * 60,\n      milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000,\n    },\n    quarters: {\n      months: 3,\n      weeks: daysInYearAccurate / 28,\n      days: daysInYearAccurate / 4,\n      hours: (daysInYearAccurate * 24) / 4,\n      minutes: (daysInYearAccurate * 24 * 60) / 4,\n      seconds: (daysInYearAccurate * 24 * 60 * 60) / 4,\n      milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4,\n    },\n    months: {\n      weeks: daysInMonthAccurate / 7,\n      days: daysInMonthAccurate,\n      hours: daysInMonthAccurate * 24,\n      minutes: daysInMonthAccurate * 24 * 60,\n      seconds: daysInMonthAccurate * 24 * 60 * 60,\n      milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000,\n    },\n    ...lowOrderMatrix,\n  };\n\n// units ordered by size\nconst orderedUnits = [\n  \"years\",\n  \"quarters\",\n  \"months\",\n  \"weeks\",\n  \"days\",\n  \"hours\",\n  \"minutes\",\n  \"seconds\",\n  \"milliseconds\",\n];\n\nconst reverseUnits = orderedUnits.slice(0).reverse();\n\n// clone really means \"create another instance just like this one, but with these changes\"\nfunction clone(dur, alts, clear = false) {\n  // deep merge for vals\n  const conf = {\n    values: clear ? alts.values : { ...dur.values, ...(alts.values || {}) },\n    loc: dur.loc.clone(alts.loc),\n    conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,\n    matrix: alts.matrix || dur.matrix,\n  };\n  return new Duration(conf);\n}\n\nfunction antiTrunc(n) {\n  return n < 0 ? Math.floor(n) : Math.ceil(n);\n}\n\n// NB: mutates parameters\nfunction convert(matrix, fromMap, fromUnit, toMap, toUnit) {\n  const conv = matrix[toUnit][fromUnit],\n    raw = fromMap[fromUnit] / conv,\n    sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]),\n    // ok, so this is wild, but see the matrix in the tests\n    added =\n      !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);\n  toMap[toUnit] += added;\n  fromMap[fromUnit] -= added * conv;\n}\n\n// NB: mutates parameters\nfunction normalizeValues(matrix, vals) {\n  reverseUnits.reduce((previous, current) => {\n    if (!isUndefined(vals[current])) {\n      if (previous) {\n        convert(matrix, vals, previous, vals, current);\n      }\n      return current;\n    } else {\n      return previous;\n    }\n  }, null);\n}\n\n// Remove all properties with a value of 0 from an object\nfunction removeZeroes(vals) {\n  const newVals = {};\n  for (const [key, value] of Object.entries(vals)) {\n    if (value !== 0) {\n      newVals[key] = value;\n    }\n  }\n  return newVals;\n}\n\n/**\n * A Duration object represents a period of time, like \"2 months\" or \"1 day, 1 hour\". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.\n *\n * Here is a brief overview of commonly used methods and getters in Duration:\n *\n * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.\n * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.\n * * **Configuration** See  {@link Duration#locale} and {@link Duration#numberingSystem} accessors.\n * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.\n * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}\n *\n * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.\n */\nexport default class Duration {\n  /**\n   * @private\n   */\n  constructor(config) {\n    const accurate = config.conversionAccuracy === \"longterm\" || false;\n    let matrix = accurate ? accurateMatrix : casualMatrix;\n\n    if (config.matrix) {\n      matrix = config.matrix;\n    }\n\n    /**\n     * @access private\n     */\n    this.values = config.values;\n    /**\n     * @access private\n     */\n    this.loc = config.loc || Locale.create();\n    /**\n     * @access private\n     */\n    this.conversionAccuracy = accurate ? \"longterm\" : \"casual\";\n    /**\n     * @access private\n     */\n    this.invalid = config.invalid || null;\n    /**\n     * @access private\n     */\n    this.matrix = matrix;\n    /**\n     * @access private\n     */\n    this.isLuxonDuration = true;\n  }\n\n  /**\n   * Create Duration from a number of milliseconds.\n   * @param {number} count of milliseconds\n   * @param {Object} opts - options for parsing\n   * @param {string} [opts.locale='en-US'] - the locale to use\n   * @param {string} opts.numberingSystem - the numbering system to use\n   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n   * @return {Duration}\n   */\n  static fromMillis(count, opts) {\n    return Duration.fromObject({ milliseconds: count }, opts);\n  }\n\n  /**\n   * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.\n   * If this object is empty then a zero milliseconds duration is returned.\n   * @param {Object} obj - the object to create the DateTime from\n   * @param {number} obj.years\n   * @param {number} obj.quarters\n   * @param {number} obj.months\n   * @param {number} obj.weeks\n   * @param {number} obj.days\n   * @param {number} obj.hours\n   * @param {number} obj.minutes\n   * @param {number} obj.seconds\n   * @param {number} obj.milliseconds\n   * @param {Object} [opts=[]] - options for creating this Duration\n   * @param {string} [opts.locale='en-US'] - the locale to use\n   * @param {string} opts.numberingSystem - the numbering system to use\n   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n   * @param {string} [opts.matrix=Object] - the custom conversion system to use\n   * @return {Duration}\n   */\n  static fromObject(obj, opts = {}) {\n    if (obj == null || typeof obj !== \"object\") {\n      throw new InvalidArgumentError(\n        `Duration.fromObject: argument expected to be an object, got ${\n          obj === null ? \"null\" : typeof obj\n        }`\n      );\n    }\n\n    return new Duration({\n      values: normalizeObject(obj, Duration.normalizeUnit),\n      loc: Locale.fromObject(opts),\n      conversionAccuracy: opts.conversionAccuracy,\n      matrix: opts.matrix,\n    });\n  }\n\n  /**\n   * Create a Duration from DurationLike.\n   *\n   * @param {Object | number | Duration} durationLike\n   * One of:\n   * - object with keys like 'years' and 'hours'.\n   * - number representing milliseconds\n   * - Duration instance\n   * @return {Duration}\n   */\n  static fromDurationLike(durationLike) {\n    if (isNumber(durationLike)) {\n      return Duration.fromMillis(durationLike);\n    } else if (Duration.isDuration(durationLike)) {\n      return durationLike;\n    } else if (typeof durationLike === \"object\") {\n      return Duration.fromObject(durationLike);\n    } else {\n      throw new InvalidArgumentError(\n        `Unknown duration argument ${durationLike} of type ${typeof durationLike}`\n      );\n    }\n  }\n\n  /**\n   * Create a Duration from an ISO 8601 duration string.\n   * @param {string} text - text to parse\n   * @param {Object} opts - options for parsing\n   * @param {string} [opts.locale='en-US'] - the locale to use\n   * @param {string} opts.numberingSystem - the numbering system to use\n   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n   * @param {string} [opts.matrix=Object] - the preset conversion system to use\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n   * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }\n   * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }\n   * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }\n   * @return {Duration}\n   */\n  static fromISO(text, opts) {\n    const [parsed] = parseISODuration(text);\n    if (parsed) {\n      return Duration.fromObject(parsed, opts);\n    } else {\n      return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n    }\n  }\n\n  /**\n   * Create a Duration from an ISO 8601 time string.\n   * @param {string} text - text to parse\n   * @param {Object} opts - options for parsing\n   * @param {string} [opts.locale='en-US'] - the locale to use\n   * @param {string} opts.numberingSystem - the numbering system to use\n   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n   * @param {string} [opts.matrix=Object] - the conversion system to use\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n   * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }\n   * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n   * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n   * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n   * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n   * @return {Duration}\n   */\n  static fromISOTime(text, opts) {\n    const [parsed] = parseISOTimeOnly(text);\n    if (parsed) {\n      return Duration.fromObject(parsed, opts);\n    } else {\n      return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n    }\n  }\n\n  /**\n   * Create an invalid Duration.\n   * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent\n   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n   * @return {Duration}\n   */\n  static invalid(reason, explanation = null) {\n    if (!reason) {\n      throw new InvalidArgumentError(\"need to specify a reason the Duration is invalid\");\n    }\n\n    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n    if (Settings.throwOnInvalid) {\n      throw new InvalidDurationError(invalid);\n    } else {\n      return new Duration({ invalid });\n    }\n  }\n\n  /**\n   * @private\n   */\n  static normalizeUnit(unit) {\n    const normalized = {\n      year: \"years\",\n      years: \"years\",\n      quarter: \"quarters\",\n      quarters: \"quarters\",\n      month: \"months\",\n      months: \"months\",\n      week: \"weeks\",\n      weeks: \"weeks\",\n      day: \"days\",\n      days: \"days\",\n      hour: \"hours\",\n      hours: \"hours\",\n      minute: \"minutes\",\n      minutes: \"minutes\",\n      second: \"seconds\",\n      seconds: \"seconds\",\n      millisecond: \"milliseconds\",\n      milliseconds: \"milliseconds\",\n    }[unit ? unit.toLowerCase() : unit];\n\n    if (!normalized) throw new InvalidUnitError(unit);\n\n    return normalized;\n  }\n\n  /**\n   * Check if an object is a Duration. Works across context boundaries\n   * @param {object} o\n   * @return {boolean}\n   */\n  static isDuration(o) {\n    return (o && o.isLuxonDuration) || false;\n  }\n\n  /**\n   * Get  the locale of a Duration, such 'en-GB'\n   * @type {string}\n   */\n  get locale() {\n    return this.isValid ? this.loc.locale : null;\n  }\n\n  /**\n   * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration\n   *\n   * @type {string}\n   */\n  get numberingSystem() {\n    return this.isValid ? this.loc.numberingSystem : null;\n  }\n\n  /**\n   * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:\n   * * `S` for milliseconds\n   * * `s` for seconds\n   * * `m` for minutes\n   * * `h` for hours\n   * * `d` for days\n   * * `w` for weeks\n   * * `M` for months\n   * * `y` for years\n   * Notes:\n   * * Add padding by repeating the token, e.g. \"yy\" pads the years to two digits, \"hhhh\" pads the hours out to four digits\n   * * Tokens can be escaped by wrapping with single quotes.\n   * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.\n   * @param {string} fmt - the format string\n   * @param {Object} opts - options\n   * @param {boolean} [opts.floor=true] - floor numerical values\n   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"y d s\") //=> \"1 6 2\"\n   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"yy dd sss\") //=> \"01 06 002\"\n   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"M S\") //=> \"12 518402000\"\n   * @return {string}\n   */\n  toFormat(fmt, opts = {}) {\n    // reverse-compat since 1.2; we always round down now, never up, and we do it by default\n    const fmtOpts = {\n      ...opts,\n      floor: opts.round !== false && opts.floor !== false,\n    };\n    return this.isValid\n      ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt)\n      : INVALID;\n  }\n\n  /**\n   * Returns a string representation of a Duration with all units included.\n   * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat\n   * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`.\n   * @example\n   * ```js\n   * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })\n   * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'\n   * dur.toHuman({ listStyle: \"long\" }) //=> '1 day, 5 hours, and 6 minutes'\n   * dur.toHuman({ unitDisplay: \"short\" }) //=> '1 day, 5 hr, 6 min'\n   * ```\n   */\n  toHuman(opts = {}) {\n    const l = orderedUnits\n      .map((unit) => {\n        const val = this.values[unit];\n        if (isUndefined(val)) {\n          return null;\n        }\n        return this.loc\n          .numberFormatter({ style: \"unit\", unitDisplay: \"long\", ...opts, unit: unit.slice(0, -1) })\n          .format(val);\n      })\n      .filter((n) => n);\n\n    return this.loc\n      .listFormatter({ type: \"conjunction\", style: opts.listStyle || \"narrow\", ...opts })\n      .format(l);\n  }\n\n  /**\n   * Returns a JavaScript object with this Duration's values.\n   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }\n   * @return {Object}\n   */\n  toObject() {\n    if (!this.isValid) return {};\n    return { ...this.values };\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this Duration.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n   * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'\n   * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'\n   * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'\n   * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'\n   * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'\n   * @return {string}\n   */\n  toISO() {\n    // we could use the formatter, but this is an easier way to get the minimum string\n    if (!this.isValid) return null;\n\n    let s = \"P\";\n    if (this.years !== 0) s += this.years + \"Y\";\n    if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + \"M\";\n    if (this.weeks !== 0) s += this.weeks + \"W\";\n    if (this.days !== 0) s += this.days + \"D\";\n    if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)\n      s += \"T\";\n    if (this.hours !== 0) s += this.hours + \"H\";\n    if (this.minutes !== 0) s += this.minutes + \"M\";\n    if (this.seconds !== 0 || this.milliseconds !== 0)\n      // this will handle \"floating point madness\" by removing extra decimal places\n      // https://stackoverflow.com/questions/588004/is-floating-point-math-broken\n      s += roundTo(this.seconds + this.milliseconds / 1000, 3) + \"S\";\n    if (s === \"P\") s += \"T0S\";\n    return s;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.\n   * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n   * @param {Object} opts - options\n   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n   * @param {string} [opts.format='extended'] - choose between the basic and extended format\n   * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'\n   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'\n   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'\n   * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'\n   * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'\n   * @return {string}\n   */\n  toISOTime(opts = {}) {\n    if (!this.isValid) return null;\n\n    const millis = this.toMillis();\n    if (millis < 0 || millis >= 86400000) return null;\n\n    opts = {\n      suppressMilliseconds: false,\n      suppressSeconds: false,\n      includePrefix: false,\n      format: \"extended\",\n      ...opts,\n    };\n\n    const value = this.shiftTo(\"hours\", \"minutes\", \"seconds\", \"milliseconds\");\n\n    let fmt = opts.format === \"basic\" ? \"hhmm\" : \"hh:mm\";\n\n    if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) {\n      fmt += opts.format === \"basic\" ? \"ss\" : \":ss\";\n      if (!opts.suppressMilliseconds || value.milliseconds !== 0) {\n        fmt += \".SSS\";\n      }\n    }\n\n    let str = value.toFormat(fmt);\n\n    if (opts.includePrefix) {\n      str = \"T\" + str;\n    }\n\n    return str;\n  }\n\n  /**\n   * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.\n   * @return {string}\n   */\n  toJSON() {\n    return this.toISO();\n  }\n\n  /**\n   * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.\n   * @return {string}\n   */\n  toString() {\n    return this.toISO();\n  }\n\n  /**\n   * Returns an milliseconds value of this Duration.\n   * @return {number}\n   */\n  toMillis() {\n    return this.as(\"milliseconds\");\n  }\n\n  /**\n   * Returns an milliseconds value of this Duration. Alias of {@link toMillis}\n   * @return {number}\n   */\n  valueOf() {\n    return this.toMillis();\n  }\n\n  /**\n   * Make this Duration longer by the specified amount. Return a newly-constructed Duration.\n   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n   * @return {Duration}\n   */\n  plus(duration) {\n    if (!this.isValid) return this;\n\n    const dur = Duration.fromDurationLike(duration),\n      result = {};\n\n    for (const k of orderedUnits) {\n      if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {\n        result[k] = dur.get(k) + this.get(k);\n      }\n    }\n\n    return clone(this, { values: result }, true);\n  }\n\n  /**\n   * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.\n   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n   * @return {Duration}\n   */\n  minus(duration) {\n    if (!this.isValid) return this;\n\n    const dur = Duration.fromDurationLike(duration);\n    return this.plus(dur.negate());\n  }\n\n  /**\n   * Scale this Duration by the specified amount. Return a newly-constructed Duration.\n   * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.\n   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }\n   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === \"hours\" ? x * 2 : x) //=> { hours: 2, minutes: 30 }\n   * @return {Duration}\n   */\n  mapUnits(fn) {\n    if (!this.isValid) return this;\n    const result = {};\n    for (const k of Object.keys(this.values)) {\n      result[k] = asNumber(fn(this.values[k], k));\n    }\n    return clone(this, { values: result }, true);\n  }\n\n  /**\n   * Get the value of unit.\n   * @param {string} unit - a unit such as 'minute' or 'day'\n   * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2\n   * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0\n   * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3\n   * @return {number}\n   */\n  get(unit) {\n    return this[Duration.normalizeUnit(unit)];\n  }\n\n  /**\n   * \"Set\" the values of specified units. Return a newly-constructed Duration.\n   * @param {Object} values - a mapping of units to numbers\n   * @example dur.set({ years: 2017 })\n   * @example dur.set({ hours: 8, minutes: 30 })\n   * @return {Duration}\n   */\n  set(values) {\n    if (!this.isValid) return this;\n\n    const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) };\n    return clone(this, { values: mixed });\n  }\n\n  /**\n   * \"Set\" the locale and/or numberingSystem.  Returns a newly-constructed Duration.\n   * @example dur.reconfigure({ locale: 'en-GB' })\n   * @return {Duration}\n   */\n  reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) {\n    const loc = this.loc.clone({ locale, numberingSystem });\n    const opts = { loc, matrix, conversionAccuracy };\n    return clone(this, opts);\n  }\n\n  /**\n   * Return the length of the duration in the specified unit.\n   * @param {string} unit - a unit such as 'minutes' or 'days'\n   * @example Duration.fromObject({years: 1}).as('days') //=> 365\n   * @example Duration.fromObject({years: 1}).as('months') //=> 12\n   * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5\n   * @return {number}\n   */\n  as(unit) {\n    return this.isValid ? this.shiftTo(unit).get(unit) : NaN;\n  }\n\n  /**\n   * Reduce this Duration to its canonical representation in its current units.\n   * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }\n   * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }\n   * @return {Duration}\n   */\n  normalize() {\n    if (!this.isValid) return this;\n    const vals = this.toObject();\n    normalizeValues(this.matrix, vals);\n    return clone(this, { values: vals }, true);\n  }\n\n  /**\n   * Rescale units to its largest representation\n   * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }\n   * @return {Duration}\n   */\n  rescale() {\n    if (!this.isValid) return this;\n    const vals = removeZeroes(this.normalize().shiftToAll().toObject());\n    return clone(this, { values: vals }, true);\n  }\n\n  /**\n   * Convert this Duration into its representation in a different set of units.\n   * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }\n   * @return {Duration}\n   */\n  shiftTo(...units) {\n    if (!this.isValid) return this;\n\n    if (units.length === 0) {\n      return this;\n    }\n\n    units = units.map((u) => Duration.normalizeUnit(u));\n\n    const built = {},\n      accumulated = {},\n      vals = this.toObject();\n    let lastUnit;\n\n    for (const k of orderedUnits) {\n      if (units.indexOf(k) >= 0) {\n        lastUnit = k;\n\n        let own = 0;\n\n        // anything we haven't boiled down yet should get boiled to this unit\n        for (const ak in accumulated) {\n          own += this.matrix[ak][k] * accumulated[ak];\n          accumulated[ak] = 0;\n        }\n\n        // plus anything that's already in this unit\n        if (isNumber(vals[k])) {\n          own += vals[k];\n        }\n\n        const i = Math.trunc(own);\n        built[k] = i;\n        accumulated[k] = (own * 1000 - i * 1000) / 1000;\n\n        // plus anything further down the chain that should be rolled up in to this\n        for (const down in vals) {\n          if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) {\n            convert(this.matrix, vals, down, built, k);\n          }\n        }\n        // otherwise, keep it in the wings to boil it later\n      } else if (isNumber(vals[k])) {\n        accumulated[k] = vals[k];\n      }\n    }\n\n    // anything leftover becomes the decimal for the last unit\n    // lastUnit must be defined since units is not empty\n    for (const key in accumulated) {\n      if (accumulated[key] !== 0) {\n        built[lastUnit] +=\n          key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];\n      }\n    }\n\n    return clone(this, { values: built }, true).normalize();\n  }\n\n  /**\n   * Shift this Duration to all available units.\n   * Same as shiftTo(\"years\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", \"seconds\", \"milliseconds\")\n   * @return {Duration}\n   */\n  shiftToAll() {\n    if (!this.isValid) return this;\n    return this.shiftTo(\n      \"years\",\n      \"months\",\n      \"weeks\",\n      \"days\",\n      \"hours\",\n      \"minutes\",\n      \"seconds\",\n      \"milliseconds\"\n    );\n  }\n\n  /**\n   * Return the negative of this Duration.\n   * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }\n   * @return {Duration}\n   */\n  negate() {\n    if (!this.isValid) return this;\n    const negated = {};\n    for (const k of Object.keys(this.values)) {\n      negated[k] = this.values[k] === 0 ? 0 : -this.values[k];\n    }\n    return clone(this, { values: negated }, true);\n  }\n\n  /**\n   * Get the years.\n   * @type {number}\n   */\n  get years() {\n    return this.isValid ? this.values.years || 0 : NaN;\n  }\n\n  /**\n   * Get the quarters.\n   * @type {number}\n   */\n  get quarters() {\n    return this.isValid ? this.values.quarters || 0 : NaN;\n  }\n\n  /**\n   * Get the months.\n   * @type {number}\n   */\n  get months() {\n    return this.isValid ? this.values.months || 0 : NaN;\n  }\n\n  /**\n   * Get the weeks\n   * @type {number}\n   */\n  get weeks() {\n    return this.isValid ? this.values.weeks || 0 : NaN;\n  }\n\n  /**\n   * Get the days.\n   * @type {number}\n   */\n  get days() {\n    return this.isValid ? this.values.days || 0 : NaN;\n  }\n\n  /**\n   * Get the hours.\n   * @type {number}\n   */\n  get hours() {\n    return this.isValid ? this.values.hours || 0 : NaN;\n  }\n\n  /**\n   * Get the minutes.\n   * @type {number}\n   */\n  get minutes() {\n    return this.isValid ? this.values.minutes || 0 : NaN;\n  }\n\n  /**\n   * Get the seconds.\n   * @return {number}\n   */\n  get seconds() {\n    return this.isValid ? this.values.seconds || 0 : NaN;\n  }\n\n  /**\n   * Get the milliseconds.\n   * @return {number}\n   */\n  get milliseconds() {\n    return this.isValid ? this.values.milliseconds || 0 : NaN;\n  }\n\n  /**\n   * Returns whether the Duration is invalid. Invalid durations are returned by diff operations\n   * on invalid DateTimes or Intervals.\n   * @return {boolean}\n   */\n  get isValid() {\n    return this.invalid === null;\n  }\n\n  /**\n   * Returns an error code if this Duration became invalid, or null if the Duration is valid\n   * @return {string}\n   */\n  get invalidReason() {\n    return this.invalid ? this.invalid.reason : null;\n  }\n\n  /**\n   * Returns an explanation of why this Duration became invalid, or null if the Duration is valid\n   * @type {string}\n   */\n  get invalidExplanation() {\n    return this.invalid ? this.invalid.explanation : null;\n  }\n\n  /**\n   * Equality check\n   * Two Durations are equal iff they have the same units and the same values for each unit.\n   * @param {Duration} other\n   * @return {boolean}\n   */\n  equals(other) {\n    if (!this.isValid || !other.isValid) {\n      return false;\n    }\n\n    if (!this.loc.equals(other.loc)) {\n      return false;\n    }\n\n    function eq(v1, v2) {\n      // Consider 0 and undefined as equal\n      if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;\n      return v1 === v2;\n    }\n\n    for (const u of orderedUnits) {\n      if (!eq(this.values[u], other.values[u])) {\n        return false;\n      }\n    }\n    return true;\n  }\n}\n","import DateTime, { friendlyDateTime } from \"./datetime.js\";\nimport Duration from \"./duration.js\";\nimport Settings from \"./settings.js\";\nimport { InvalidArgumentError, InvalidIntervalError } from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport * as Formats from \"./impl/formats.js\";\n\nconst INVALID = \"Invalid Interval\";\n\n// checks if the start is equal to or before the end\nfunction validateStartEnd(start, end) {\n  if (!start || !start.isValid) {\n    return Interval.invalid(\"missing or invalid start\");\n  } else if (!end || !end.isValid) {\n    return Interval.invalid(\"missing or invalid end\");\n  } else if (end < start) {\n    return Interval.invalid(\n      \"end before start\",\n      `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`\n    );\n  } else {\n    return null;\n  }\n}\n\n/**\n * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.\n *\n * Here is a brief overview of the most commonly used methods and getters in Interval:\n *\n * * **Creation** To create an Interval, use {@link Interval.fromDateTimes}, {@link Interval.after}, {@link Interval.before}, or {@link Interval.fromISO}.\n * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end.\n * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}.\n * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval.merge}, {@link Interval.xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}.\n * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs}\n * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toLocaleString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}.\n */\nexport default class Interval {\n  /**\n   * @private\n   */\n  constructor(config) {\n    /**\n     * @access private\n     */\n    this.s = config.start;\n    /**\n     * @access private\n     */\n    this.e = config.end;\n    /**\n     * @access private\n     */\n    this.invalid = config.invalid || null;\n    /**\n     * @access private\n     */\n    this.isLuxonInterval = true;\n  }\n\n  /**\n   * Create an invalid Interval.\n   * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent\n   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n   * @return {Interval}\n   */\n  static invalid(reason, explanation = null) {\n    if (!reason) {\n      throw new InvalidArgumentError(\"need to specify a reason the Interval is invalid\");\n    }\n\n    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n    if (Settings.throwOnInvalid) {\n      throw new InvalidIntervalError(invalid);\n    } else {\n      return new Interval({ invalid });\n    }\n  }\n\n  /**\n   * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.\n   * @param {DateTime|Date|Object} start\n   * @param {DateTime|Date|Object} end\n   * @return {Interval}\n   */\n  static fromDateTimes(start, end) {\n    const builtStart = friendlyDateTime(start),\n      builtEnd = friendlyDateTime(end);\n\n    const validateError = validateStartEnd(builtStart, builtEnd);\n\n    if (validateError == null) {\n      return new Interval({\n        start: builtStart,\n        end: builtEnd,\n      });\n    } else {\n      return validateError;\n    }\n  }\n\n  /**\n   * Create an Interval from a start DateTime and a Duration to extend to.\n   * @param {DateTime|Date|Object} start\n   * @param {Duration|Object|number} duration - the length of the Interval.\n   * @return {Interval}\n   */\n  static after(start, duration) {\n    const dur = Duration.fromDurationLike(duration),\n      dt = friendlyDateTime(start);\n    return Interval.fromDateTimes(dt, dt.plus(dur));\n  }\n\n  /**\n   * Create an Interval from an end DateTime and a Duration to extend backwards to.\n   * @param {DateTime|Date|Object} end\n   * @param {Duration|Object|number} duration - the length of the Interval.\n   * @return {Interval}\n   */\n  static before(end, duration) {\n    const dur = Duration.fromDurationLike(duration),\n      dt = friendlyDateTime(end);\n    return Interval.fromDateTimes(dt.minus(dur), dt);\n  }\n\n  /**\n   * Create an Interval from an ISO 8601 string.\n   * Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats.\n   * @param {string} text - the ISO string to parse\n   * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n   * @return {Interval}\n   */\n  static fromISO(text, opts) {\n    const [s, e] = (text || \"\").split(\"/\", 2);\n    if (s && e) {\n      let start, startIsValid;\n      try {\n        start = DateTime.fromISO(s, opts);\n        startIsValid = start.isValid;\n      } catch (e) {\n        startIsValid = false;\n      }\n\n      let end, endIsValid;\n      try {\n        end = DateTime.fromISO(e, opts);\n        endIsValid = end.isValid;\n      } catch (e) {\n        endIsValid = false;\n      }\n\n      if (startIsValid && endIsValid) {\n        return Interval.fromDateTimes(start, end);\n      }\n\n      if (startIsValid) {\n        const dur = Duration.fromISO(e, opts);\n        if (dur.isValid) {\n          return Interval.after(start, dur);\n        }\n      } else if (endIsValid) {\n        const dur = Duration.fromISO(s, opts);\n        if (dur.isValid) {\n          return Interval.before(end, dur);\n        }\n      }\n    }\n    return Interval.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n  }\n\n  /**\n   * Check if an object is an Interval. Works across context boundaries\n   * @param {object} o\n   * @return {boolean}\n   */\n  static isInterval(o) {\n    return (o && o.isLuxonInterval) || false;\n  }\n\n  /**\n   * Returns the start of the Interval\n   * @type {DateTime}\n   */\n  get start() {\n    return this.isValid ? this.s : null;\n  }\n\n  /**\n   * Returns the end of the Interval\n   * @type {DateTime}\n   */\n  get end() {\n    return this.isValid ? this.e : null;\n  }\n\n  /**\n   * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.\n   * @type {boolean}\n   */\n  get isValid() {\n    return this.invalidReason === null;\n  }\n\n  /**\n   * Returns an error code if this Interval is invalid, or null if the Interval is valid\n   * @type {string}\n   */\n  get invalidReason() {\n    return this.invalid ? this.invalid.reason : null;\n  }\n\n  /**\n   * Returns an explanation of why this Interval became invalid, or null if the Interval is valid\n   * @type {string}\n   */\n  get invalidExplanation() {\n    return this.invalid ? this.invalid.explanation : null;\n  }\n\n  /**\n   * Returns the length of the Interval in the specified unit.\n   * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.\n   * @return {number}\n   */\n  length(unit = \"milliseconds\") {\n    return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;\n  }\n\n  /**\n   * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.\n   * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'\n   * asks 'what dates are included in this interval?', not 'how many days long is this interval?'\n   * @param {string} [unit='milliseconds'] - the unit of time to count.\n   * @return {number}\n   */\n  count(unit = \"milliseconds\") {\n    if (!this.isValid) return NaN;\n    const start = this.start.startOf(unit),\n      end = this.end.startOf(unit);\n    return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf());\n  }\n\n  /**\n   * Returns whether this Interval's start and end are both in the same unit of time\n   * @param {string} unit - the unit of time to check sameness on\n   * @return {boolean}\n   */\n  hasSame(unit) {\n    return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;\n  }\n\n  /**\n   * Return whether this Interval has the same start and end DateTimes.\n   * @return {boolean}\n   */\n  isEmpty() {\n    return this.s.valueOf() === this.e.valueOf();\n  }\n\n  /**\n   * Return whether this Interval's start is after the specified DateTime.\n   * @param {DateTime} dateTime\n   * @return {boolean}\n   */\n  isAfter(dateTime) {\n    if (!this.isValid) return false;\n    return this.s > dateTime;\n  }\n\n  /**\n   * Return whether this Interval's end is before the specified DateTime.\n   * @param {DateTime} dateTime\n   * @return {boolean}\n   */\n  isBefore(dateTime) {\n    if (!this.isValid) return false;\n    return this.e <= dateTime;\n  }\n\n  /**\n   * Return whether this Interval contains the specified DateTime.\n   * @param {DateTime} dateTime\n   * @return {boolean}\n   */\n  contains(dateTime) {\n    if (!this.isValid) return false;\n    return this.s <= dateTime && this.e > dateTime;\n  }\n\n  /**\n   * \"Sets\" the start and/or end dates. Returns a newly-constructed Interval.\n   * @param {Object} values - the values to set\n   * @param {DateTime} values.start - the starting DateTime\n   * @param {DateTime} values.end - the ending DateTime\n   * @return {Interval}\n   */\n  set({ start, end } = {}) {\n    if (!this.isValid) return this;\n    return Interval.fromDateTimes(start || this.s, end || this.e);\n  }\n\n  /**\n   * Split this Interval at each of the specified DateTimes\n   * @param {...DateTime} dateTimes - the unit of time to count.\n   * @return {Array}\n   */\n  splitAt(...dateTimes) {\n    if (!this.isValid) return [];\n    const sorted = dateTimes\n        .map(friendlyDateTime)\n        .filter((d) => this.contains(d))\n        .sort(),\n      results = [];\n    let { s } = this,\n      i = 0;\n\n    while (s < this.e) {\n      const added = sorted[i] || this.e,\n        next = +added > +this.e ? this.e : added;\n      results.push(Interval.fromDateTimes(s, next));\n      s = next;\n      i += 1;\n    }\n\n    return results;\n  }\n\n  /**\n   * Split this Interval into smaller Intervals, each of the specified length.\n   * Left over time is grouped into a smaller interval\n   * @param {Duration|Object|number} duration - The length of each resulting interval.\n   * @return {Array}\n   */\n  splitBy(duration) {\n    const dur = Duration.fromDurationLike(duration);\n\n    if (!this.isValid || !dur.isValid || dur.as(\"milliseconds\") === 0) {\n      return [];\n    }\n\n    let { s } = this,\n      idx = 1,\n      next;\n\n    const results = [];\n    while (s < this.e) {\n      const added = this.start.plus(dur.mapUnits((x) => x * idx));\n      next = +added > +this.e ? this.e : added;\n      results.push(Interval.fromDateTimes(s, next));\n      s = next;\n      idx += 1;\n    }\n\n    return results;\n  }\n\n  /**\n   * Split this Interval into the specified number of smaller intervals.\n   * @param {number} numberOfParts - The number of Intervals to divide the Interval into.\n   * @return {Array}\n   */\n  divideEqually(numberOfParts) {\n    if (!this.isValid) return [];\n    return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);\n  }\n\n  /**\n   * Return whether this Interval overlaps with the specified Interval\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  overlaps(other) {\n    return this.e > other.s && this.s < other.e;\n  }\n\n  /**\n   * Return whether this Interval's end is adjacent to the specified Interval's start.\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  abutsStart(other) {\n    if (!this.isValid) return false;\n    return +this.e === +other.s;\n  }\n\n  /**\n   * Return whether this Interval's start is adjacent to the specified Interval's end.\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  abutsEnd(other) {\n    if (!this.isValid) return false;\n    return +other.e === +this.s;\n  }\n\n  /**\n   * Return whether this Interval engulfs the start and end of the specified Interval.\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  engulfs(other) {\n    if (!this.isValid) return false;\n    return this.s <= other.s && this.e >= other.e;\n  }\n\n  /**\n   * Return whether this Interval has the same start and end as the specified Interval.\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  equals(other) {\n    if (!this.isValid || !other.isValid) {\n      return false;\n    }\n\n    return this.s.equals(other.s) && this.e.equals(other.e);\n  }\n\n  /**\n   * Return an Interval representing the intersection of this Interval and the specified Interval.\n   * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.\n   * Returns null if the intersection is empty, meaning, the intervals don't intersect.\n   * @param {Interval} other\n   * @return {Interval}\n   */\n  intersection(other) {\n    if (!this.isValid) return this;\n    const s = this.s > other.s ? this.s : other.s,\n      e = this.e < other.e ? this.e : other.e;\n\n    if (s >= e) {\n      return null;\n    } else {\n      return Interval.fromDateTimes(s, e);\n    }\n  }\n\n  /**\n   * Return an Interval representing the union of this Interval and the specified Interval.\n   * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.\n   * @param {Interval} other\n   * @return {Interval}\n   */\n  union(other) {\n    if (!this.isValid) return this;\n    const s = this.s < other.s ? this.s : other.s,\n      e = this.e > other.e ? this.e : other.e;\n    return Interval.fromDateTimes(s, e);\n  }\n\n  /**\n   * Merge an array of Intervals into a equivalent minimal set of Intervals.\n   * Combines overlapping and adjacent Intervals.\n   * @param {Array} intervals\n   * @return {Array}\n   */\n  static merge(intervals) {\n    const [found, final] = intervals\n      .sort((a, b) => a.s - b.s)\n      .reduce(\n        ([sofar, current], item) => {\n          if (!current) {\n            return [sofar, item];\n          } else if (current.overlaps(item) || current.abutsStart(item)) {\n            return [sofar, current.union(item)];\n          } else {\n            return [sofar.concat([current]), item];\n          }\n        },\n        [[], null]\n      );\n    if (final) {\n      found.push(final);\n    }\n    return found;\n  }\n\n  /**\n   * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.\n   * @param {Array} intervals\n   * @return {Array}\n   */\n  static xor(intervals) {\n    let start = null,\n      currentCount = 0;\n    const results = [],\n      ends = intervals.map((i) => [\n        { time: i.s, type: \"s\" },\n        { time: i.e, type: \"e\" },\n      ]),\n      flattened = Array.prototype.concat(...ends),\n      arr = flattened.sort((a, b) => a.time - b.time);\n\n    for (const i of arr) {\n      currentCount += i.type === \"s\" ? 1 : -1;\n\n      if (currentCount === 1) {\n        start = i.time;\n      } else {\n        if (start && +start !== +i.time) {\n          results.push(Interval.fromDateTimes(start, i.time));\n        }\n\n        start = null;\n      }\n    }\n\n    return Interval.merge(results);\n  }\n\n  /**\n   * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.\n   * @param {...Interval} intervals\n   * @return {Array}\n   */\n  difference(...intervals) {\n    return Interval.xor([this].concat(intervals))\n      .map((i) => this.intersection(i))\n      .filter((i) => i && !i.isEmpty());\n  }\n\n  /**\n   * Returns a string representation of this Interval appropriate for debugging.\n   * @return {string}\n   */\n  toString() {\n    if (!this.isValid) return INVALID;\n    return `[${this.s.toISO()} – ${this.e.toISO()})`;\n  }\n\n  /**\n   * Returns a localized string representing this Interval. Accepts the same options as the\n   * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as\n   * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method\n   * is browser-specific, but in general it will return an appropriate representation of the\n   * Interval in the assigned locale. Defaults to the system's locale if no locale has been\n   * specified.\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n   * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or\n   * Intl.DateTimeFormat constructor options.\n   * @param {Object} opts - Options to override the configuration of the start DateTime.\n   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022\n   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022\n   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022\n   * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM\n   * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p\n   * @return {string}\n   */\n  toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {\n    return this.isValid\n      ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this)\n      : INVALID;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this Interval.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n   * @param {Object} opts - The same options as {@link DateTime#toISO}\n   * @return {string}\n   */\n  toISO(opts) {\n    if (!this.isValid) return INVALID;\n    return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of date of this Interval.\n   * The time components are ignored.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n   * @return {string}\n   */\n  toISODate() {\n    if (!this.isValid) return INVALID;\n    return `${this.s.toISODate()}/${this.e.toISODate()}`;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of time of this Interval.\n   * The date components are ignored.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n   * @param {Object} opts - The same options as {@link DateTime#toISO}\n   * @return {string}\n   */\n  toISOTime(opts) {\n    if (!this.isValid) return INVALID;\n    return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;\n  }\n\n  /**\n   * Returns a string representation of this Interval formatted according to the specified format\n   * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible\n   * formatting tool.\n   * @param {string} dateFormat - The format string. This string formats the start and end time.\n   * See {@link DateTime#toFormat} for details.\n   * @param {Object} opts - Options.\n   * @param {string} [opts.separator =  ' – '] - A separator to place between the start and end\n   * representations.\n   * @return {string}\n   */\n  toFormat(dateFormat, { separator = \" – \" } = {}) {\n    if (!this.isValid) return INVALID;\n    return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;\n  }\n\n  /**\n   * Return a Duration representing the time spanned by this interval.\n   * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.\n   * @param {Object} opts - options that affect the creation of the Duration\n   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }\n   * @return {Duration}\n   */\n  toDuration(unit, opts) {\n    if (!this.isValid) {\n      return Duration.invalid(this.invalidReason);\n    }\n    return this.e.diff(this.s, unit, opts);\n  }\n\n  /**\n   * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes\n   * @param {function} mapFn\n   * @return {Interval}\n   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())\n   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))\n   */\n  mapEndpoints(mapFn) {\n    return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));\n  }\n}\n","import DateTime from \"./datetime.js\";\nimport Settings from \"./settings.js\";\nimport Locale from \"./impl/locale.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\n\nimport { hasRelative } from \"./impl/util.js\";\n\n/**\n * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.\n */\nexport default class Info {\n  /**\n   * Return whether the specified zone contains a DST.\n   * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.\n   * @return {boolean}\n   */\n  static hasDST(zone = Settings.defaultZone) {\n    const proto = DateTime.now().setZone(zone).set({ month: 12 });\n\n    return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;\n  }\n\n  /**\n   * Return whether the specified zone is a valid IANA specifier.\n   * @param {string} zone - Zone to check\n   * @return {boolean}\n   */\n  static isValidIANAZone(zone) {\n    return IANAZone.isValidZone(zone);\n  }\n\n  /**\n   * Converts the input into a {@link Zone} instance.\n   *\n   * * If `input` is already a Zone instance, it is returned unchanged.\n   * * If `input` is a string containing a valid time zone name, a Zone instance\n   *   with that name is returned.\n   * * If `input` is a string that doesn't refer to a known time zone, a Zone\n   *   instance with {@link Zone#isValid} == false is returned.\n   * * If `input is a number, a Zone instance with the specified fixed offset\n   *   in minutes is returned.\n   * * If `input` is `null` or `undefined`, the default zone is returned.\n   * @param {string|Zone|number} [input] - the value to be converted\n   * @return {Zone}\n   */\n  static normalizeZone(input) {\n    return normalizeZone(input, Settings.defaultZone);\n  }\n\n  /**\n   * Return an array of standalone month names.\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n   * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @param {string} [opts.numberingSystem=null] - the numbering system\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @param {string} [opts.outputCalendar='gregory'] - the calendar\n   * @example Info.months()[0] //=> 'January'\n   * @example Info.months('short')[0] //=> 'Jan'\n   * @example Info.months('numeric')[0] //=> '1'\n   * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'\n   * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'\n   * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'\n   * @return {Array}\n   */\n  static months(\n    length = \"long\",\n    { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n  ) {\n    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);\n  }\n\n  /**\n   * Return an array of format month names.\n   * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that\n   * changes the string.\n   * See {@link Info#months}\n   * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @param {string} [opts.numberingSystem=null] - the numbering system\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @param {string} [opts.outputCalendar='gregory'] - the calendar\n   * @return {Array}\n   */\n  static monthsFormat(\n    length = \"long\",\n    { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n  ) {\n    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);\n  }\n\n  /**\n   * Return an array of standalone week names.\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n   * @param {string} [length='long'] - the length of the weekday representation, such as \"narrow\", \"short\", \"long\".\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @param {string} [opts.numberingSystem=null] - the numbering system\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @example Info.weekdays()[0] //=> 'Monday'\n   * @example Info.weekdays('short')[0] //=> 'Mon'\n   * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'\n   * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'\n   * @return {Array}\n   */\n  static weekdays(length = \"long\", { locale = null, numberingSystem = null, locObj = null } = {}) {\n    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);\n  }\n\n  /**\n   * Return an array of format week names.\n   * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that\n   * changes the string.\n   * See {@link Info#weekdays}\n   * @param {string} [length='long'] - the length of the month representation, such as \"narrow\", \"short\", \"long\".\n   * @param {Object} opts - options\n   * @param {string} [opts.locale=null] - the locale code\n   * @param {string} [opts.numberingSystem=null] - the numbering system\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @return {Array}\n   */\n  static weekdaysFormat(\n    length = \"long\",\n    { locale = null, numberingSystem = null, locObj = null } = {}\n  ) {\n    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);\n  }\n\n  /**\n   * Return an array of meridiems.\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @example Info.meridiems() //=> [ 'AM', 'PM' ]\n   * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]\n   * @return {Array}\n   */\n  static meridiems({ locale = null } = {}) {\n    return Locale.create(locale).meridiems();\n  }\n\n  /**\n   * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.\n   * @param {string} [length='short'] - the length of the era representation, such as \"short\" or \"long\".\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @example Info.eras() //=> [ 'BC', 'AD' ]\n   * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]\n   * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]\n   * @return {Array}\n   */\n  static eras(length = \"short\", { locale = null } = {}) {\n    return Locale.create(locale, null, \"gregory\").eras(length);\n  }\n\n  /**\n   * Return the set of available features in this environment.\n   * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.\n   * Keys:\n   * * `relative`: whether this environment supports relative time formatting\n   * @example Info.features() //=> { relative: false }\n   * @return {Object}\n   */\n  static features() {\n    return { relative: hasRelative() };\n  }\n}\n","import Duration from \"../duration.js\";\n\nfunction dayDiff(earlier, later) {\n  const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf(\"day\").valueOf(),\n    ms = utcDayStart(later) - utcDayStart(earlier);\n  return Math.floor(Duration.fromMillis(ms).as(\"days\"));\n}\n\nfunction highOrderDiffs(cursor, later, units) {\n  const differs = [\n    [\"years\", (a, b) => b.year - a.year],\n    [\"quarters\", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4],\n    [\"months\", (a, b) => b.month - a.month + (b.year - a.year) * 12],\n    [\n      \"weeks\",\n      (a, b) => {\n        const days = dayDiff(a, b);\n        return (days - (days % 7)) / 7;\n      },\n    ],\n    [\"days\", dayDiff],\n  ];\n\n  const results = {};\n  const earlier = cursor;\n  let lowestOrder, highWater;\n\n  for (const [unit, differ] of differs) {\n    if (units.indexOf(unit) >= 0) {\n      lowestOrder = unit;\n\n      results[unit] = differ(cursor, later);\n      highWater = earlier.plus(results);\n\n      if (highWater > later) {\n        results[unit]--;\n        cursor = earlier.plus(results);\n      } else {\n        cursor = highWater;\n      }\n    }\n  }\n\n  return [cursor, results, highWater, lowestOrder];\n}\n\nexport default function (earlier, later, units, opts) {\n  let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);\n\n  const remainingMillis = later - cursor;\n\n  const lowerOrderUnits = units.filter(\n    (u) => [\"hours\", \"minutes\", \"seconds\", \"milliseconds\"].indexOf(u) >= 0\n  );\n\n  if (lowerOrderUnits.length === 0) {\n    if (highWater < later) {\n      highWater = cursor.plus({ [lowestOrder]: 1 });\n    }\n\n    if (highWater !== cursor) {\n      results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);\n    }\n  }\n\n  const duration = Duration.fromObject(results, opts);\n\n  if (lowerOrderUnits.length > 0) {\n    return Duration.fromMillis(remainingMillis, opts)\n      .shiftTo(...lowerOrderUnits)\n      .plus(duration);\n  } else {\n    return duration;\n  }\n}\n","const numberingSystems = {\n  arab: \"[\\u0660-\\u0669]\",\n  arabext: \"[\\u06F0-\\u06F9]\",\n  bali: \"[\\u1B50-\\u1B59]\",\n  beng: \"[\\u09E6-\\u09EF]\",\n  deva: \"[\\u0966-\\u096F]\",\n  fullwide: \"[\\uFF10-\\uFF19]\",\n  gujr: \"[\\u0AE6-\\u0AEF]\",\n  hanidec: \"[〇|一|二|三|四|五|六|七|八|九]\",\n  khmr: \"[\\u17E0-\\u17E9]\",\n  knda: \"[\\u0CE6-\\u0CEF]\",\n  laoo: \"[\\u0ED0-\\u0ED9]\",\n  limb: \"[\\u1946-\\u194F]\",\n  mlym: \"[\\u0D66-\\u0D6F]\",\n  mong: \"[\\u1810-\\u1819]\",\n  mymr: \"[\\u1040-\\u1049]\",\n  orya: \"[\\u0B66-\\u0B6F]\",\n  tamldec: \"[\\u0BE6-\\u0BEF]\",\n  telu: \"[\\u0C66-\\u0C6F]\",\n  thai: \"[\\u0E50-\\u0E59]\",\n  tibt: \"[\\u0F20-\\u0F29]\",\n  latn: \"\\\\d\",\n};\n\nconst numberingSystemsUTF16 = {\n  arab: [1632, 1641],\n  arabext: [1776, 1785],\n  bali: [6992, 7001],\n  beng: [2534, 2543],\n  deva: [2406, 2415],\n  fullwide: [65296, 65303],\n  gujr: [2790, 2799],\n  khmr: [6112, 6121],\n  knda: [3302, 3311],\n  laoo: [3792, 3801],\n  limb: [6470, 6479],\n  mlym: [3430, 3439],\n  mong: [6160, 6169],\n  mymr: [4160, 4169],\n  orya: [2918, 2927],\n  tamldec: [3046, 3055],\n  telu: [3174, 3183],\n  thai: [3664, 3673],\n  tibt: [3872, 3881],\n};\n\nconst hanidecChars = numberingSystems.hanidec.replace(/[\\[|\\]]/g, \"\").split(\"\");\n\nexport function parseDigits(str) {\n  let value = parseInt(str, 10);\n  if (isNaN(value)) {\n    value = \"\";\n    for (let i = 0; i < str.length; i++) {\n      const code = str.charCodeAt(i);\n\n      if (str[i].search(numberingSystems.hanidec) !== -1) {\n        value += hanidecChars.indexOf(str[i]);\n      } else {\n        for (const key in numberingSystemsUTF16) {\n          const [min, max] = numberingSystemsUTF16[key];\n          if (code >= min && code <= max) {\n            value += code - min;\n          }\n        }\n      }\n    }\n    return parseInt(value, 10);\n  } else {\n    return value;\n  }\n}\n\nexport function digitRegex({ numberingSystem }, append = \"\") {\n  return new RegExp(`${numberingSystems[numberingSystem || \"latn\"]}${append}`);\n}\n","import { parseMillis, isUndefined, untruncateYear, signedOffset, hasOwnProperty } from \"./util.js\";\nimport Formatter from \"./formatter.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport DateTime from \"../datetime.js\";\nimport { digitRegex, parseDigits } from \"./digits.js\";\nimport { ConflictingSpecificationError } from \"../errors.js\";\n\nconst MISSING_FTP = \"missing Intl.DateTimeFormat.formatToParts support\";\n\nfunction intUnit(regex, post = (i) => i) {\n  return { regex, deser: ([s]) => post(parseDigits(s)) };\n}\n\nconst NBSP = String.fromCharCode(160);\nconst spaceOrNBSP = `[ ${NBSP}]`;\nconst spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, \"g\");\n\nfunction fixListRegex(s) {\n  // make dots optional and also make them literal\n  // make space and non breakable space characters interchangeable\n  return s.replace(/\\./g, \"\\\\.?\").replace(spaceOrNBSPRegExp, spaceOrNBSP);\n}\n\nfunction stripInsensitivities(s) {\n  return s\n    .replace(/\\./g, \"\") // ignore dots that were made optional\n    .replace(spaceOrNBSPRegExp, \" \") // interchange space and nbsp\n    .toLowerCase();\n}\n\nfunction oneOf(strings, startIndex) {\n  if (strings === null) {\n    return null;\n  } else {\n    return {\n      regex: RegExp(strings.map(fixListRegex).join(\"|\")),\n      deser: ([s]) =>\n        strings.findIndex((i) => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex,\n    };\n  }\n}\n\nfunction offset(regex, groups) {\n  return { regex, deser: ([, h, m]) => signedOffset(h, m), groups };\n}\n\nfunction simple(regex) {\n  return { regex, deser: ([s]) => s };\n}\n\nfunction escapeToken(value) {\n  return value.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g, \"\\\\$&\");\n}\n\nfunction unitForToken(token, loc) {\n  const one = digitRegex(loc),\n    two = digitRegex(loc, \"{2}\"),\n    three = digitRegex(loc, \"{3}\"),\n    four = digitRegex(loc, \"{4}\"),\n    six = digitRegex(loc, \"{6}\"),\n    oneOrTwo = digitRegex(loc, \"{1,2}\"),\n    oneToThree = digitRegex(loc, \"{1,3}\"),\n    oneToSix = digitRegex(loc, \"{1,6}\"),\n    oneToNine = digitRegex(loc, \"{1,9}\"),\n    twoToFour = digitRegex(loc, \"{2,4}\"),\n    fourToSix = digitRegex(loc, \"{4,6}\"),\n    literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s]) => s, literal: true }),\n    unitate = (t) => {\n      if (token.literal) {\n        return literal(t);\n      }\n      switch (t.val) {\n        // era\n        case \"G\":\n          return oneOf(loc.eras(\"short\", false), 0);\n        case \"GG\":\n          return oneOf(loc.eras(\"long\", false), 0);\n        // years\n        case \"y\":\n          return intUnit(oneToSix);\n        case \"yy\":\n          return intUnit(twoToFour, untruncateYear);\n        case \"yyyy\":\n          return intUnit(four);\n        case \"yyyyy\":\n          return intUnit(fourToSix);\n        case \"yyyyyy\":\n          return intUnit(six);\n        // months\n        case \"M\":\n          return intUnit(oneOrTwo);\n        case \"MM\":\n          return intUnit(two);\n        case \"MMM\":\n          return oneOf(loc.months(\"short\", true, false), 1);\n        case \"MMMM\":\n          return oneOf(loc.months(\"long\", true, false), 1);\n        case \"L\":\n          return intUnit(oneOrTwo);\n        case \"LL\":\n          return intUnit(two);\n        case \"LLL\":\n          return oneOf(loc.months(\"short\", false, false), 1);\n        case \"LLLL\":\n          return oneOf(loc.months(\"long\", false, false), 1);\n        // dates\n        case \"d\":\n          return intUnit(oneOrTwo);\n        case \"dd\":\n          return intUnit(two);\n        // ordinals\n        case \"o\":\n          return intUnit(oneToThree);\n        case \"ooo\":\n          return intUnit(three);\n        // time\n        case \"HH\":\n          return intUnit(two);\n        case \"H\":\n          return intUnit(oneOrTwo);\n        case \"hh\":\n          return intUnit(two);\n        case \"h\":\n          return intUnit(oneOrTwo);\n        case \"mm\":\n          return intUnit(two);\n        case \"m\":\n          return intUnit(oneOrTwo);\n        case \"q\":\n          return intUnit(oneOrTwo);\n        case \"qq\":\n          return intUnit(two);\n        case \"s\":\n          return intUnit(oneOrTwo);\n        case \"ss\":\n          return intUnit(two);\n        case \"S\":\n          return intUnit(oneToThree);\n        case \"SSS\":\n          return intUnit(three);\n        case \"u\":\n          return simple(oneToNine);\n        case \"uu\":\n          return simple(oneOrTwo);\n        case \"uuu\":\n          return intUnit(one);\n        // meridiem\n        case \"a\":\n          return oneOf(loc.meridiems(), 0);\n        // weekYear (k)\n        case \"kkkk\":\n          return intUnit(four);\n        case \"kk\":\n          return intUnit(twoToFour, untruncateYear);\n        // weekNumber (W)\n        case \"W\":\n          return intUnit(oneOrTwo);\n        case \"WW\":\n          return intUnit(two);\n        // weekdays\n        case \"E\":\n        case \"c\":\n          return intUnit(one);\n        case \"EEE\":\n          return oneOf(loc.weekdays(\"short\", false, false), 1);\n        case \"EEEE\":\n          return oneOf(loc.weekdays(\"long\", false, false), 1);\n        case \"ccc\":\n          return oneOf(loc.weekdays(\"short\", true, false), 1);\n        case \"cccc\":\n          return oneOf(loc.weekdays(\"long\", true, false), 1);\n        // offset/zone\n        case \"Z\":\n        case \"ZZ\":\n          return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);\n        case \"ZZZ\":\n          return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);\n        // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing\n        // because we don't have any way to figure out what they are\n        case \"z\":\n          return simple(/[a-z_+-/]{1,256}?/i);\n        // this special-case \"token\" represents a place where a macro-token expanded into a white-space literal\n        // in this case we accept any non-newline white-space\n        case \" \":\n          return simple(/[^\\S\\n\\r]/);\n        default:\n          return literal(t);\n      }\n    };\n\n  const unit = unitate(token) || {\n    invalidReason: MISSING_FTP,\n  };\n\n  unit.token = token;\n\n  return unit;\n}\n\nconst partTypeStyleToTokenVal = {\n  year: {\n    \"2-digit\": \"yy\",\n    numeric: \"yyyyy\",\n  },\n  month: {\n    numeric: \"M\",\n    \"2-digit\": \"MM\",\n    short: \"MMM\",\n    long: \"MMMM\",\n  },\n  day: {\n    numeric: \"d\",\n    \"2-digit\": \"dd\",\n  },\n  weekday: {\n    short: \"EEE\",\n    long: \"EEEE\",\n  },\n  dayperiod: \"a\",\n  dayPeriod: \"a\",\n  hour: {\n    numeric: \"h\",\n    \"2-digit\": \"hh\",\n  },\n  minute: {\n    numeric: \"m\",\n    \"2-digit\": \"mm\",\n  },\n  second: {\n    numeric: \"s\",\n    \"2-digit\": \"ss\",\n  },\n  timeZoneName: {\n    long: \"ZZZZZ\",\n    short: \"ZZZ\",\n  },\n};\n\nfunction tokenForPart(part, formatOpts) {\n  const { type, value } = part;\n\n  if (type === \"literal\") {\n    const isSpace = /^\\s+$/.test(value);\n    return {\n      literal: !isSpace,\n      val: isSpace ? \" \" : value,\n    };\n  }\n\n  const style = formatOpts[type];\n\n  let val = partTypeStyleToTokenVal[type];\n  if (typeof val === \"object\") {\n    val = val[style];\n  }\n\n  if (val) {\n    return {\n      literal: false,\n      val,\n    };\n  }\n\n  return undefined;\n}\n\nfunction buildRegex(units) {\n  const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, \"\");\n  return [`^${re}$`, units];\n}\n\nfunction match(input, regex, handlers) {\n  const matches = input.match(regex);\n\n  if (matches) {\n    const all = {};\n    let matchIndex = 1;\n    for (const i in handlers) {\n      if (hasOwnProperty(handlers, i)) {\n        const h = handlers[i],\n          groups = h.groups ? h.groups + 1 : 1;\n        if (!h.literal && h.token) {\n          all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));\n        }\n        matchIndex += groups;\n      }\n    }\n    return [matches, all];\n  } else {\n    return [matches, {}];\n  }\n}\n\nfunction dateTimeFromMatches(matches) {\n  const toField = (token) => {\n    switch (token) {\n      case \"S\":\n        return \"millisecond\";\n      case \"s\":\n        return \"second\";\n      case \"m\":\n        return \"minute\";\n      case \"h\":\n      case \"H\":\n        return \"hour\";\n      case \"d\":\n        return \"day\";\n      case \"o\":\n        return \"ordinal\";\n      case \"L\":\n      case \"M\":\n        return \"month\";\n      case \"y\":\n        return \"year\";\n      case \"E\":\n      case \"c\":\n        return \"weekday\";\n      case \"W\":\n        return \"weekNumber\";\n      case \"k\":\n        return \"weekYear\";\n      case \"q\":\n        return \"quarter\";\n      default:\n        return null;\n    }\n  };\n\n  let zone = null;\n  let specificOffset;\n  if (!isUndefined(matches.z)) {\n    zone = IANAZone.create(matches.z);\n  }\n\n  if (!isUndefined(matches.Z)) {\n    if (!zone) {\n      zone = new FixedOffsetZone(matches.Z);\n    }\n    specificOffset = matches.Z;\n  }\n\n  if (!isUndefined(matches.q)) {\n    matches.M = (matches.q - 1) * 3 + 1;\n  }\n\n  if (!isUndefined(matches.h)) {\n    if (matches.h < 12 && matches.a === 1) {\n      matches.h += 12;\n    } else if (matches.h === 12 && matches.a === 0) {\n      matches.h = 0;\n    }\n  }\n\n  if (matches.G === 0 && matches.y) {\n    matches.y = -matches.y;\n  }\n\n  if (!isUndefined(matches.u)) {\n    matches.S = parseMillis(matches.u);\n  }\n\n  const vals = Object.keys(matches).reduce((r, k) => {\n    const f = toField(k);\n    if (f) {\n      r[f] = matches[k];\n    }\n\n    return r;\n  }, {});\n\n  return [vals, zone, specificOffset];\n}\n\nlet dummyDateTimeCache = null;\n\nfunction getDummyDateTime() {\n  if (!dummyDateTimeCache) {\n    dummyDateTimeCache = DateTime.fromMillis(1555555555555);\n  }\n\n  return dummyDateTimeCache;\n}\n\nfunction maybeExpandMacroToken(token, locale) {\n  if (token.literal) {\n    return token;\n  }\n\n  const formatOpts = Formatter.macroTokenToFormatOpts(token.val);\n  const tokens = formatOptsToTokens(formatOpts, locale);\n\n  if (tokens == null || tokens.includes(undefined)) {\n    return token;\n  }\n\n  return tokens;\n}\n\nexport function expandMacroTokens(tokens, locale) {\n  return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale)));\n}\n\n/**\n * @private\n */\n\nexport function explainFromTokens(locale, input, format) {\n  const tokens = expandMacroTokens(Formatter.parseFormat(format), locale),\n    units = tokens.map((t) => unitForToken(t, locale)),\n    disqualifyingUnit = units.find((t) => t.invalidReason);\n\n  if (disqualifyingUnit) {\n    return { input, tokens, invalidReason: disqualifyingUnit.invalidReason };\n  } else {\n    const [regexString, handlers] = buildRegex(units),\n      regex = RegExp(regexString, \"i\"),\n      [rawMatches, matches] = match(input, regex, handlers),\n      [result, zone, specificOffset] = matches\n        ? dateTimeFromMatches(matches)\n        : [null, null, undefined];\n    if (hasOwnProperty(matches, \"a\") && hasOwnProperty(matches, \"H\")) {\n      throw new ConflictingSpecificationError(\n        \"Can't include meridiem when specifying 24-hour format\"\n      );\n    }\n    return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset };\n  }\n}\n\nexport function parseFromTokens(locale, input, format) {\n  const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format);\n  return [result, zone, specificOffset, invalidReason];\n}\n\nexport function formatOptsToTokens(formatOpts, locale) {\n  if (!formatOpts) {\n    return null;\n  }\n\n  const formatter = Formatter.create(locale, formatOpts);\n  const parts = formatter.formatDateTimeParts(getDummyDateTime());\n  return parts.map((p) => tokenForPart(p, formatOpts));\n}\n","import {\n  integerBetween,\n  isLeapYear,\n  timeObject,\n  daysInYear,\n  daysInMonth,\n  weeksInWeekYear,\n  isInteger,\n} from \"./util.js\";\nimport Invalid from \"./invalid.js\";\n\nconst nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],\n  leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\n\nfunction unitOutOfRange(unit, value) {\n  return new Invalid(\n    \"unit out of range\",\n    `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`\n  );\n}\n\nfunction dayOfWeek(year, month, day) {\n  const d = new Date(Date.UTC(year, month - 1, day));\n\n  if (year < 100 && year >= 0) {\n    d.setUTCFullYear(d.getUTCFullYear() - 1900);\n  }\n\n  const js = d.getUTCDay();\n\n  return js === 0 ? 7 : js;\n}\n\nfunction computeOrdinal(year, month, day) {\n  return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];\n}\n\nfunction uncomputeOrdinal(year, ordinal) {\n  const table = isLeapYear(year) ? leapLadder : nonLeapLadder,\n    month0 = table.findIndex((i) => i < ordinal),\n    day = ordinal - table[month0];\n  return { month: month0 + 1, day };\n}\n\n/**\n * @private\n */\n\nexport function gregorianToWeek(gregObj) {\n  const { year, month, day } = gregObj,\n    ordinal = computeOrdinal(year, month, day),\n    weekday = dayOfWeek(year, month, day);\n\n  let weekNumber = Math.floor((ordinal - weekday + 10) / 7),\n    weekYear;\n\n  if (weekNumber < 1) {\n    weekYear = year - 1;\n    weekNumber = weeksInWeekYear(weekYear);\n  } else if (weekNumber > weeksInWeekYear(year)) {\n    weekYear = year + 1;\n    weekNumber = 1;\n  } else {\n    weekYear = year;\n  }\n\n  return { weekYear, weekNumber, weekday, ...timeObject(gregObj) };\n}\n\nexport function weekToGregorian(weekData) {\n  const { weekYear, weekNumber, weekday } = weekData,\n    weekdayOfJan4 = dayOfWeek(weekYear, 1, 4),\n    yearInDays = daysInYear(weekYear);\n\n  let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3,\n    year;\n\n  if (ordinal < 1) {\n    year = weekYear - 1;\n    ordinal += daysInYear(year);\n  } else if (ordinal > yearInDays) {\n    year = weekYear + 1;\n    ordinal -= daysInYear(weekYear);\n  } else {\n    year = weekYear;\n  }\n\n  const { month, day } = uncomputeOrdinal(year, ordinal);\n  return { year, month, day, ...timeObject(weekData) };\n}\n\nexport function gregorianToOrdinal(gregData) {\n  const { year, month, day } = gregData;\n  const ordinal = computeOrdinal(year, month, day);\n  return { year, ordinal, ...timeObject(gregData) };\n}\n\nexport function ordinalToGregorian(ordinalData) {\n  const { year, ordinal } = ordinalData;\n  const { month, day } = uncomputeOrdinal(year, ordinal);\n  return { year, month, day, ...timeObject(ordinalData) };\n}\n\nexport function hasInvalidWeekData(obj) {\n  const validYear = isInteger(obj.weekYear),\n    validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)),\n    validWeekday = integerBetween(obj.weekday, 1, 7);\n\n  if (!validYear) {\n    return unitOutOfRange(\"weekYear\", obj.weekYear);\n  } else if (!validWeek) {\n    return unitOutOfRange(\"week\", obj.week);\n  } else if (!validWeekday) {\n    return unitOutOfRange(\"weekday\", obj.weekday);\n  } else return false;\n}\n\nexport function hasInvalidOrdinalData(obj) {\n  const validYear = isInteger(obj.year),\n    validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));\n\n  if (!validYear) {\n    return unitOutOfRange(\"year\", obj.year);\n  } else if (!validOrdinal) {\n    return unitOutOfRange(\"ordinal\", obj.ordinal);\n  } else return false;\n}\n\nexport function hasInvalidGregorianData(obj) {\n  const validYear = isInteger(obj.year),\n    validMonth = integerBetween(obj.month, 1, 12),\n    validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));\n\n  if (!validYear) {\n    return unitOutOfRange(\"year\", obj.year);\n  } else if (!validMonth) {\n    return unitOutOfRange(\"month\", obj.month);\n  } else if (!validDay) {\n    return unitOutOfRange(\"day\", obj.day);\n  } else return false;\n}\n\nexport function hasInvalidTimeData(obj) {\n  const { hour, minute, second, millisecond } = obj;\n  const validHour =\n      integerBetween(hour, 0, 23) ||\n      (hour === 24 && minute === 0 && second === 0 && millisecond === 0),\n    validMinute = integerBetween(minute, 0, 59),\n    validSecond = integerBetween(second, 0, 59),\n    validMillisecond = integerBetween(millisecond, 0, 999);\n\n  if (!validHour) {\n    return unitOutOfRange(\"hour\", hour);\n  } else if (!validMinute) {\n    return unitOutOfRange(\"minute\", minute);\n  } else if (!validSecond) {\n    return unitOutOfRange(\"second\", second);\n  } else if (!validMillisecond) {\n    return unitOutOfRange(\"millisecond\", millisecond);\n  } else return false;\n}\n","import Duration from \"./duration.js\";\nimport Interval from \"./interval.js\";\nimport Settings from \"./settings.js\";\nimport Info from \"./info.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport FixedOffsetZone from \"./zones/fixedOffsetZone.js\";\nimport Locale from \"./impl/locale.js\";\nimport {\n  isUndefined,\n  maybeArray,\n  isDate,\n  isNumber,\n  bestBy,\n  daysInMonth,\n  daysInYear,\n  isLeapYear,\n  weeksInWeekYear,\n  normalizeObject,\n  roundTo,\n  objToLocalTS,\n  padStart,\n} from \"./impl/util.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\nimport diff from \"./impl/diff.js\";\nimport { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from \"./impl/regexParser.js\";\nimport {\n  parseFromTokens,\n  explainFromTokens,\n  formatOptsToTokens,\n  expandMacroTokens,\n} from \"./impl/tokenParser.js\";\nimport {\n  gregorianToWeek,\n  weekToGregorian,\n  gregorianToOrdinal,\n  ordinalToGregorian,\n  hasInvalidGregorianData,\n  hasInvalidWeekData,\n  hasInvalidOrdinalData,\n  hasInvalidTimeData,\n} from \"./impl/conversions.js\";\nimport * as Formats from \"./impl/formats.js\";\nimport {\n  InvalidArgumentError,\n  ConflictingSpecificationError,\n  InvalidUnitError,\n  InvalidDateTimeError,\n} from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\n\nconst INVALID = \"Invalid DateTime\";\nconst MAX_DATE = 8.64e15;\n\nfunction unsupportedZone(zone) {\n  return new Invalid(\"unsupported zone\", `the zone \"${zone.name}\" is not supported`);\n}\n\n// we cache week data on the DT object and this intermediates the cache\nfunction possiblyCachedWeekData(dt) {\n  if (dt.weekData === null) {\n    dt.weekData = gregorianToWeek(dt.c);\n  }\n  return dt.weekData;\n}\n\n// clone really means, \"make a new object with these modifications\". all \"setters\" really use this\n// to create a new object while only changing some of the properties\nfunction clone(inst, alts) {\n  const current = {\n    ts: inst.ts,\n    zone: inst.zone,\n    c: inst.c,\n    o: inst.o,\n    loc: inst.loc,\n    invalid: inst.invalid,\n  };\n  return new DateTime({ ...current, ...alts, old: current });\n}\n\n// find the right offset a given local time. The o input is our guess, which determines which\n// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)\nfunction fixOffset(localTS, o, tz) {\n  // Our UTC time is just a guess because our offset is just a guess\n  let utcGuess = localTS - o * 60 * 1000;\n\n  // Test whether the zone matches the offset for this ts\n  const o2 = tz.offset(utcGuess);\n\n  // If so, offset didn't change and we're done\n  if (o === o2) {\n    return [utcGuess, o];\n  }\n\n  // If not, change the ts by the difference in the offset\n  utcGuess -= (o2 - o) * 60 * 1000;\n\n  // If that gives us the local time we want, we're done\n  const o3 = tz.offset(utcGuess);\n  if (o2 === o3) {\n    return [utcGuess, o2];\n  }\n\n  // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time\n  return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];\n}\n\n// convert an epoch timestamp into a calendar object with the given offset\nfunction tsToObj(ts, offset) {\n  ts += offset * 60 * 1000;\n\n  const d = new Date(ts);\n\n  return {\n    year: d.getUTCFullYear(),\n    month: d.getUTCMonth() + 1,\n    day: d.getUTCDate(),\n    hour: d.getUTCHours(),\n    minute: d.getUTCMinutes(),\n    second: d.getUTCSeconds(),\n    millisecond: d.getUTCMilliseconds(),\n  };\n}\n\n// convert a calendar object to a epoch timestamp\nfunction objToTS(obj, offset, zone) {\n  return fixOffset(objToLocalTS(obj), offset, zone);\n}\n\n// create a new DT instance by adding a duration, adjusting for DSTs\nfunction adjustTime(inst, dur) {\n  const oPre = inst.o,\n    year = inst.c.year + Math.trunc(dur.years),\n    month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,\n    c = {\n      ...inst.c,\n      year,\n      month,\n      day:\n        Math.min(inst.c.day, daysInMonth(year, month)) +\n        Math.trunc(dur.days) +\n        Math.trunc(dur.weeks) * 7,\n    },\n    millisToAdd = Duration.fromObject({\n      years: dur.years - Math.trunc(dur.years),\n      quarters: dur.quarters - Math.trunc(dur.quarters),\n      months: dur.months - Math.trunc(dur.months),\n      weeks: dur.weeks - Math.trunc(dur.weeks),\n      days: dur.days - Math.trunc(dur.days),\n      hours: dur.hours,\n      minutes: dur.minutes,\n      seconds: dur.seconds,\n      milliseconds: dur.milliseconds,\n    }).as(\"milliseconds\"),\n    localTS = objToLocalTS(c);\n\n  let [ts, o] = fixOffset(localTS, oPre, inst.zone);\n\n  if (millisToAdd !== 0) {\n    ts += millisToAdd;\n    // that could have changed the offset by going over a DST, but we want to keep the ts the same\n    o = inst.zone.offset(ts);\n  }\n\n  return { ts, o };\n}\n\n// helper useful in turning the results of parsing into real dates\n// by handling the zone options\nfunction parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {\n  const { setZone, zone } = opts;\n  if ((parsed && Object.keys(parsed).length !== 0) || parsedZone) {\n    const interpretationZone = parsedZone || zone,\n      inst = DateTime.fromObject(parsed, {\n        ...opts,\n        zone: interpretationZone,\n        specificOffset,\n      });\n    return setZone ? inst : inst.setZone(zone);\n  } else {\n    return DateTime.invalid(\n      new Invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ${format}`)\n    );\n  }\n}\n\n// if you want to output a technical format (e.g. RFC 2822), this helper\n// helps handle the details\nfunction toTechFormat(dt, format, allowZ = true) {\n  return dt.isValid\n    ? Formatter.create(Locale.create(\"en-US\"), {\n        allowZ,\n        forceSimple: true,\n      }).formatDateTimeFromString(dt, format)\n    : null;\n}\n\nfunction toISODate(o, extended) {\n  const longFormat = o.c.year > 9999 || o.c.year < 0;\n  let c = \"\";\n  if (longFormat && o.c.year >= 0) c += \"+\";\n  c += padStart(o.c.year, longFormat ? 6 : 4);\n\n  if (extended) {\n    c += \"-\";\n    c += padStart(o.c.month);\n    c += \"-\";\n    c += padStart(o.c.day);\n  } else {\n    c += padStart(o.c.month);\n    c += padStart(o.c.day);\n  }\n  return c;\n}\n\nfunction toISOTime(\n  o,\n  extended,\n  suppressSeconds,\n  suppressMilliseconds,\n  includeOffset,\n  extendedZone\n) {\n  let c = padStart(o.c.hour);\n  if (extended) {\n    c += \":\";\n    c += padStart(o.c.minute);\n    if (o.c.second !== 0 || !suppressSeconds) {\n      c += \":\";\n    }\n  } else {\n    c += padStart(o.c.minute);\n  }\n\n  if (o.c.second !== 0 || !suppressSeconds) {\n    c += padStart(o.c.second);\n\n    if (o.c.millisecond !== 0 || !suppressMilliseconds) {\n      c += \".\";\n      c += padStart(o.c.millisecond, 3);\n    }\n  }\n\n  if (includeOffset) {\n    if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {\n      c += \"Z\";\n    } else if (o.o < 0) {\n      c += \"-\";\n      c += padStart(Math.trunc(-o.o / 60));\n      c += \":\";\n      c += padStart(Math.trunc(-o.o % 60));\n    } else {\n      c += \"+\";\n      c += padStart(Math.trunc(o.o / 60));\n      c += \":\";\n      c += padStart(Math.trunc(o.o % 60));\n    }\n  }\n\n  if (extendedZone) {\n    c += \"[\" + o.zone.ianaName + \"]\";\n  }\n  return c;\n}\n\n// defaults for unspecified units in the supported calendars\nconst defaultUnitValues = {\n    month: 1,\n    day: 1,\n    hour: 0,\n    minute: 0,\n    second: 0,\n    millisecond: 0,\n  },\n  defaultWeekUnitValues = {\n    weekNumber: 1,\n    weekday: 1,\n    hour: 0,\n    minute: 0,\n    second: 0,\n    millisecond: 0,\n  },\n  defaultOrdinalUnitValues = {\n    ordinal: 1,\n    hour: 0,\n    minute: 0,\n    second: 0,\n    millisecond: 0,\n  };\n\n// Units in the supported calendars, sorted by bigness\nconst orderedUnits = [\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"millisecond\"],\n  orderedWeekUnits = [\n    \"weekYear\",\n    \"weekNumber\",\n    \"weekday\",\n    \"hour\",\n    \"minute\",\n    \"second\",\n    \"millisecond\",\n  ],\n  orderedOrdinalUnits = [\"year\", \"ordinal\", \"hour\", \"minute\", \"second\", \"millisecond\"];\n\n// standardize case and plurality in units\nfunction normalizeUnit(unit) {\n  const normalized = {\n    year: \"year\",\n    years: \"year\",\n    month: \"month\",\n    months: \"month\",\n    day: \"day\",\n    days: \"day\",\n    hour: \"hour\",\n    hours: \"hour\",\n    minute: \"minute\",\n    minutes: \"minute\",\n    quarter: \"quarter\",\n    quarters: \"quarter\",\n    second: \"second\",\n    seconds: \"second\",\n    millisecond: \"millisecond\",\n    milliseconds: \"millisecond\",\n    weekday: \"weekday\",\n    weekdays: \"weekday\",\n    weeknumber: \"weekNumber\",\n    weeksnumber: \"weekNumber\",\n    weeknumbers: \"weekNumber\",\n    weekyear: \"weekYear\",\n    weekyears: \"weekYear\",\n    ordinal: \"ordinal\",\n  }[unit.toLowerCase()];\n\n  if (!normalized) throw new InvalidUnitError(unit);\n\n  return normalized;\n}\n\n// this is a dumbed down version of fromObject() that runs about 60% faster\n// but doesn't do any validation, makes a bunch of assumptions about what units\n// are present, and so on.\nfunction quickDT(obj, opts) {\n  const zone = normalizeZone(opts.zone, Settings.defaultZone),\n    loc = Locale.fromObject(opts),\n    tsNow = Settings.now();\n\n  let ts, o;\n\n  // assume we have the higher-order units\n  if (!isUndefined(obj.year)) {\n    for (const u of orderedUnits) {\n      if (isUndefined(obj[u])) {\n        obj[u] = defaultUnitValues[u];\n      }\n    }\n\n    const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);\n    if (invalid) {\n      return DateTime.invalid(invalid);\n    }\n\n    const offsetProvis = zone.offset(tsNow);\n    [ts, o] = objToTS(obj, offsetProvis, zone);\n  } else {\n    ts = tsNow;\n  }\n\n  return new DateTime({ ts, zone, loc, o });\n}\n\nfunction diffRelative(start, end, opts) {\n  const round = isUndefined(opts.round) ? true : opts.round,\n    format = (c, unit) => {\n      c = roundTo(c, round || opts.calendary ? 0 : 2, true);\n      const formatter = end.loc.clone(opts).relFormatter(opts);\n      return formatter.format(c, unit);\n    },\n    differ = (unit) => {\n      if (opts.calendary) {\n        if (!end.hasSame(start, unit)) {\n          return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);\n        } else return 0;\n      } else {\n        return end.diff(start, unit).get(unit);\n      }\n    };\n\n  if (opts.unit) {\n    return format(differ(opts.unit), opts.unit);\n  }\n\n  for (const unit of opts.units) {\n    const count = differ(unit);\n    if (Math.abs(count) >= 1) {\n      return format(count, unit);\n    }\n  }\n  return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);\n}\n\nfunction lastOpts(argList) {\n  let opts = {},\n    args;\n  if (argList.length > 0 && typeof argList[argList.length - 1] === \"object\") {\n    opts = argList[argList.length - 1];\n    args = Array.from(argList).slice(0, argList.length - 1);\n  } else {\n    args = Array.from(argList);\n  }\n  return [opts, args];\n}\n\n/**\n * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.\n *\n * A DateTime comprises of:\n * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.\n * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).\n * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.\n *\n * Here is a brief overview of the most commonly used functionality it provides:\n *\n * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}.\n * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},\n * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.\n * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.\n * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.\n * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.\n * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.\n *\n * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.\n */\nexport default class DateTime {\n  /**\n   * @access private\n   */\n  constructor(config) {\n    const zone = config.zone || Settings.defaultZone;\n\n    let invalid =\n      config.invalid ||\n      (Number.isNaN(config.ts) ? new Invalid(\"invalid input\") : null) ||\n      (!zone.isValid ? unsupportedZone(zone) : null);\n    /**\n     * @access private\n     */\n    this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;\n\n    let c = null,\n      o = null;\n    if (!invalid) {\n      const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);\n\n      if (unchanged) {\n        [c, o] = [config.old.c, config.old.o];\n      } else {\n        const ot = zone.offset(this.ts);\n        c = tsToObj(this.ts, ot);\n        invalid = Number.isNaN(c.year) ? new Invalid(\"invalid input\") : null;\n        c = invalid ? null : c;\n        o = invalid ? null : ot;\n      }\n    }\n\n    /**\n     * @access private\n     */\n    this._zone = zone;\n    /**\n     * @access private\n     */\n    this.loc = config.loc || Locale.create();\n    /**\n     * @access private\n     */\n    this.invalid = invalid;\n    /**\n     * @access private\n     */\n    this.weekData = null;\n    /**\n     * @access private\n     */\n    this.c = c;\n    /**\n     * @access private\n     */\n    this.o = o;\n    /**\n     * @access private\n     */\n    this.isLuxonDateTime = true;\n  }\n\n  // CONSTRUCT\n\n  /**\n   * Create a DateTime for the current instant, in the system's time zone.\n   *\n   * Use Settings to override these default values if needed.\n   * @example DateTime.now().toISO() //~> now in the ISO format\n   * @return {DateTime}\n   */\n  static now() {\n    return new DateTime({});\n  }\n\n  /**\n   * Create a local DateTime\n   * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used\n   * @param {number} [month=1] - The month, 1-indexed\n   * @param {number} [day=1] - The day of the month, 1-indexed\n   * @param {number} [hour=0] - The hour of the day, in 24-hour time\n   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n   * @example DateTime.local()                                  //~> now\n   * @example DateTime.local({ zone: \"America/New_York\" })      //~> now, in US east coast time\n   * @example DateTime.local(2017)                              //~> 2017-01-01T00:00:00\n   * @example DateTime.local(2017, 3)                           //~> 2017-03-01T00:00:00\n   * @example DateTime.local(2017, 3, 12, { locale: \"fr\" })     //~> 2017-03-12T00:00:00, with a French locale\n   * @example DateTime.local(2017, 3, 12, 5)                    //~> 2017-03-12T05:00:00\n   * @example DateTime.local(2017, 3, 12, 5, { zone: \"utc\" })   //~> 2017-03-12T05:00:00, in UTC\n   * @example DateTime.local(2017, 3, 12, 5, 45)                //~> 2017-03-12T05:45:00\n   * @example DateTime.local(2017, 3, 12, 5, 45, 10)            //~> 2017-03-12T05:45:10\n   * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765)       //~> 2017-03-12T05:45:10.765\n   * @return {DateTime}\n   */\n  static local() {\n    const [opts, args] = lastOpts(arguments),\n      [year, month, day, hour, minute, second, millisecond] = args;\n    return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n  }\n\n  /**\n   * Create a DateTime in UTC\n   * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used\n   * @param {number} [month=1] - The month, 1-indexed\n   * @param {number} [day=1] - The day of the month\n   * @param {number} [hour=0] - The hour of the day, in 24-hour time\n   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n   * @param {Object} options - configuration options for the DateTime\n   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n   * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance\n   * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance\n   * @example DateTime.utc()                                              //~> now\n   * @example DateTime.utc(2017)                                          //~> 2017-01-01T00:00:00Z\n   * @example DateTime.utc(2017, 3)                                       //~> 2017-03-01T00:00:00Z\n   * @example DateTime.utc(2017, 3, 12)                                   //~> 2017-03-12T00:00:00Z\n   * @example DateTime.utc(2017, 3, 12, 5)                                //~> 2017-03-12T05:00:00Z\n   * @example DateTime.utc(2017, 3, 12, 5, 45)                            //~> 2017-03-12T05:45:00Z\n   * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: \"fr\" })          //~> 2017-03-12T05:45:00Z with a French locale\n   * @example DateTime.utc(2017, 3, 12, 5, 45, 10)                        //~> 2017-03-12T05:45:10Z\n   * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: \"fr\" }) //~> 2017-03-12T05:45:10.765Z with a French locale\n   * @return {DateTime}\n   */\n  static utc() {\n    const [opts, args] = lastOpts(arguments),\n      [year, month, day, hour, minute, second, millisecond] = args;\n\n    opts.zone = FixedOffsetZone.utcInstance;\n    return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n  }\n\n  /**\n   * Create a DateTime from a JavaScript Date object. Uses the default zone.\n   * @param {Date} date - a JavaScript Date object\n   * @param {Object} options - configuration options for the DateTime\n   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n   * @return {DateTime}\n   */\n  static fromJSDate(date, options = {}) {\n    const ts = isDate(date) ? date.valueOf() : NaN;\n    if (Number.isNaN(ts)) {\n      return DateTime.invalid(\"invalid input\");\n    }\n\n    const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);\n    if (!zoneToUse.isValid) {\n      return DateTime.invalid(unsupportedZone(zoneToUse));\n    }\n\n    return new DateTime({\n      ts: ts,\n      zone: zoneToUse,\n      loc: Locale.fromObject(options),\n    });\n  }\n\n  /**\n   * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n   * @param {number} milliseconds - a number of milliseconds since 1970 UTC\n   * @param {Object} options - configuration options for the DateTime\n   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @return {DateTime}\n   */\n  static fromMillis(milliseconds, options = {}) {\n    if (!isNumber(milliseconds)) {\n      throw new InvalidArgumentError(\n        `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`\n      );\n    } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {\n      // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start\n      return DateTime.invalid(\"Timestamp out of range\");\n    } else {\n      return new DateTime({\n        ts: milliseconds,\n        zone: normalizeZone(options.zone, Settings.defaultZone),\n        loc: Locale.fromObject(options),\n      });\n    }\n  }\n\n  /**\n   * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n   * @param {number} seconds - a number of seconds since 1970 UTC\n   * @param {Object} options - configuration options for the DateTime\n   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @return {DateTime}\n   */\n  static fromSeconds(seconds, options = {}) {\n    if (!isNumber(seconds)) {\n      throw new InvalidArgumentError(\"fromSeconds requires a numerical input\");\n    } else {\n      return new DateTime({\n        ts: seconds * 1000,\n        zone: normalizeZone(options.zone, Settings.defaultZone),\n        loc: Locale.fromObject(options),\n      });\n    }\n  }\n\n  /**\n   * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.\n   * @param {Object} obj - the object to create the DateTime from\n   * @param {number} obj.year - a year, such as 1987\n   * @param {number} obj.month - a month, 1-12\n   * @param {number} obj.day - a day of the month, 1-31, depending on the month\n   * @param {number} obj.ordinal - day of the year, 1-365 or 366\n   * @param {number} obj.weekYear - an ISO week year\n   * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year\n   * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday\n   * @param {number} obj.hour - hour of the day, 0-23\n   * @param {number} obj.minute - minute of the hour, 0-59\n   * @param {number} obj.second - second of the minute, 0-59\n   * @param {number} obj.millisecond - millisecond of the second, 0-999\n   * @param {Object} opts - options for creating this DateTime\n   * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()\n   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'\n   * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'\n   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06\n   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),\n   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })\n   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })\n   * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'\n   * @return {DateTime}\n   */\n  static fromObject(obj, opts = {}) {\n    obj = obj || {};\n    const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);\n    if (!zoneToUse.isValid) {\n      return DateTime.invalid(unsupportedZone(zoneToUse));\n    }\n\n    const tsNow = Settings.now(),\n      offsetProvis = !isUndefined(opts.specificOffset)\n        ? opts.specificOffset\n        : zoneToUse.offset(tsNow),\n      normalized = normalizeObject(obj, normalizeUnit),\n      containsOrdinal = !isUndefined(normalized.ordinal),\n      containsGregorYear = !isUndefined(normalized.year),\n      containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n      containsGregor = containsGregorYear || containsGregorMD,\n      definiteWeekDef = normalized.weekYear || normalized.weekNumber,\n      loc = Locale.fromObject(opts);\n\n    // cases:\n    // just a weekday -> this week's instance of that weekday, no worries\n    // (gregorian data or ordinal) + (weekYear or weekNumber) -> error\n    // (gregorian month or day) + ordinal -> error\n    // otherwise just use weeks or ordinals or gregorian, depending on what's specified\n\n    if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n      throw new ConflictingSpecificationError(\n        \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n      );\n    }\n\n    if (containsGregorMD && containsOrdinal) {\n      throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n    }\n\n    const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);\n\n    // configure ourselves to deal with gregorian dates or week stuff\n    let units,\n      defaultValues,\n      objNow = tsToObj(tsNow, offsetProvis);\n    if (useWeekData) {\n      units = orderedWeekUnits;\n      defaultValues = defaultWeekUnitValues;\n      objNow = gregorianToWeek(objNow);\n    } else if (containsOrdinal) {\n      units = orderedOrdinalUnits;\n      defaultValues = defaultOrdinalUnitValues;\n      objNow = gregorianToOrdinal(objNow);\n    } else {\n      units = orderedUnits;\n      defaultValues = defaultUnitValues;\n    }\n\n    // set default values for missing stuff\n    let foundFirst = false;\n    for (const u of units) {\n      const v = normalized[u];\n      if (!isUndefined(v)) {\n        foundFirst = true;\n      } else if (foundFirst) {\n        normalized[u] = defaultValues[u];\n      } else {\n        normalized[u] = objNow[u];\n      }\n    }\n\n    // make sure the values we have are in range\n    const higherOrderInvalid = useWeekData\n        ? hasInvalidWeekData(normalized)\n        : containsOrdinal\n        ? hasInvalidOrdinalData(normalized)\n        : hasInvalidGregorianData(normalized),\n      invalid = higherOrderInvalid || hasInvalidTimeData(normalized);\n\n    if (invalid) {\n      return DateTime.invalid(invalid);\n    }\n\n    // compute the actual time\n    const gregorian = useWeekData\n        ? weekToGregorian(normalized)\n        : containsOrdinal\n        ? ordinalToGregorian(normalized)\n        : normalized,\n      [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),\n      inst = new DateTime({\n        ts: tsFinal,\n        zone: zoneToUse,\n        o: offsetFinal,\n        loc,\n      });\n\n    // gregorian data + weekday serves only to validate\n    if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {\n      return DateTime.invalid(\n        \"mismatched weekday\",\n        `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`\n      );\n    }\n\n    return inst;\n  }\n\n  /**\n   * Create a DateTime from an ISO 8601 string\n   * @param {string} text - the ISO string\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone\n   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n   * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance\n   * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance\n   * @example DateTime.fromISO('2016-05-25T09:08:34.123')\n   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')\n   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})\n   * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})\n   * @example DateTime.fromISO('2016-W05-4')\n   * @return {DateTime}\n   */\n  static fromISO(text, opts = {}) {\n    const [vals, parsedZone] = parseISODate(text);\n    return parseDataToDateTime(vals, parsedZone, opts, \"ISO 8601\", text);\n  }\n\n  /**\n   * Create a DateTime from an RFC 2822 string\n   * @param {string} text - the RFC 2822 string\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')\n   * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')\n   * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')\n   * @return {DateTime}\n   */\n  static fromRFC2822(text, opts = {}) {\n    const [vals, parsedZone] = parseRFC2822Date(text);\n    return parseDataToDateTime(vals, parsedZone, opts, \"RFC 2822\", text);\n  }\n\n  /**\n   * Create a DateTime from an HTTP header date\n   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n   * @param {string} text - the HTTP header date\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n   * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.\n   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')\n   * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')\n   * @example DateTime.fromHTTP('Sun Nov  6 08:49:37 1994')\n   * @return {DateTime}\n   */\n  static fromHTTP(text, opts = {}) {\n    const [vals, parsedZone] = parseHTTPDate(text);\n    return parseDataToDateTime(vals, parsedZone, opts, \"HTTP\", opts);\n  }\n\n  /**\n   * Create a DateTime from an input string and format string.\n   * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).\n   * @param {string} text - the string to parse\n   * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @return {DateTime}\n   */\n  static fromFormat(text, fmt, opts = {}) {\n    if (isUndefined(text) || isUndefined(fmt)) {\n      throw new InvalidArgumentError(\"fromFormat requires an input string and a format\");\n    }\n\n    const { locale = null, numberingSystem = null } = opts,\n      localeToUse = Locale.fromOpts({\n        locale,\n        numberingSystem,\n        defaultToEN: true,\n      }),\n      [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);\n    if (invalid) {\n      return DateTime.invalid(invalid);\n    } else {\n      return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);\n    }\n  }\n\n  /**\n   * @deprecated use fromFormat instead\n   */\n  static fromString(text, fmt, opts = {}) {\n    return DateTime.fromFormat(text, fmt, opts);\n  }\n\n  /**\n   * Create a DateTime from a SQL date, time, or datetime\n   * Defaults to en-US if no locale has been specified, regardless of the system's locale\n   * @param {string} text - the string to parse\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @example DateTime.fromSQL('2017-05-15')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })\n   * @example DateTime.fromSQL('09:12:34.342')\n   * @return {DateTime}\n   */\n  static fromSQL(text, opts = {}) {\n    const [vals, parsedZone] = parseSQL(text);\n    return parseDataToDateTime(vals, parsedZone, opts, \"SQL\", text);\n  }\n\n  /**\n   * Create an invalid DateTime.\n   * @param {DateTime} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent\n   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n   * @return {DateTime}\n   */\n  static invalid(reason, explanation = null) {\n    if (!reason) {\n      throw new InvalidArgumentError(\"need to specify a reason the DateTime is invalid\");\n    }\n\n    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n    if (Settings.throwOnInvalid) {\n      throw new InvalidDateTimeError(invalid);\n    } else {\n      return new DateTime({ invalid });\n    }\n  }\n\n  /**\n   * Check if an object is an instance of DateTime. Works across context boundaries\n   * @param {object} o\n   * @return {boolean}\n   */\n  static isDateTime(o) {\n    return (o && o.isLuxonDateTime) || false;\n  }\n\n  /**\n   * Produce the format string for a set of options\n   * @param formatOpts\n   * @param localeOpts\n   * @returns {string}\n   */\n  static parseFormatForOpts(formatOpts, localeOpts = {}) {\n    const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));\n    return !tokenList ? null : tokenList.map((t) => (t ? t.val : null)).join(\"\");\n  }\n\n  /**\n   * Produce the the fully expanded format token for the locale\n   * Does NOT quote characters, so quoted tokens will not round trip correctly\n   * @param fmt\n   * @param localeOpts\n   * @returns {string}\n   */\n  static expandFormat(fmt, localeOpts = {}) {\n    const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));\n    return expanded.map((t) => t.val).join(\"\");\n  }\n\n  // INFO\n\n  /**\n   * Get the value of unit.\n   * @param {string} unit - a unit such as 'minute' or 'day'\n   * @example DateTime.local(2017, 7, 4).get('month'); //=> 7\n   * @example DateTime.local(2017, 7, 4).get('day'); //=> 4\n   * @return {number}\n   */\n  get(unit) {\n    return this[unit];\n  }\n\n  /**\n   * Returns whether the DateTime is valid. Invalid DateTimes occur when:\n   * * The DateTime was created from invalid calendar information, such as the 13th month or February 30\n   * * The DateTime was created by an operation on another invalid date\n   * @type {boolean}\n   */\n  get isValid() {\n    return this.invalid === null;\n  }\n\n  /**\n   * Returns an error code if this DateTime is invalid, or null if the DateTime is valid\n   * @type {string}\n   */\n  get invalidReason() {\n    return this.invalid ? this.invalid.reason : null;\n  }\n\n  /**\n   * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid\n   * @type {string}\n   */\n  get invalidExplanation() {\n    return this.invalid ? this.invalid.explanation : null;\n  }\n\n  /**\n   * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime\n   *\n   * @type {string}\n   */\n  get locale() {\n    return this.isValid ? this.loc.locale : null;\n  }\n\n  /**\n   * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime\n   *\n   * @type {string}\n   */\n  get numberingSystem() {\n    return this.isValid ? this.loc.numberingSystem : null;\n  }\n\n  /**\n   * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime\n   *\n   * @type {string}\n   */\n  get outputCalendar() {\n    return this.isValid ? this.loc.outputCalendar : null;\n  }\n\n  /**\n   * Get the time zone associated with this DateTime.\n   * @type {Zone}\n   */\n  get zone() {\n    return this._zone;\n  }\n\n  /**\n   * Get the name of the time zone.\n   * @type {string}\n   */\n  get zoneName() {\n    return this.isValid ? this.zone.name : null;\n  }\n\n  /**\n   * Get the year\n   * @example DateTime.local(2017, 5, 25).year //=> 2017\n   * @type {number}\n   */\n  get year() {\n    return this.isValid ? this.c.year : NaN;\n  }\n\n  /**\n   * Get the quarter\n   * @example DateTime.local(2017, 5, 25).quarter //=> 2\n   * @type {number}\n   */\n  get quarter() {\n    return this.isValid ? Math.ceil(this.c.month / 3) : NaN;\n  }\n\n  /**\n   * Get the month (1-12).\n   * @example DateTime.local(2017, 5, 25).month //=> 5\n   * @type {number}\n   */\n  get month() {\n    return this.isValid ? this.c.month : NaN;\n  }\n\n  /**\n   * Get the day of the month (1-30ish).\n   * @example DateTime.local(2017, 5, 25).day //=> 25\n   * @type {number}\n   */\n  get day() {\n    return this.isValid ? this.c.day : NaN;\n  }\n\n  /**\n   * Get the hour of the day (0-23).\n   * @example DateTime.local(2017, 5, 25, 9).hour //=> 9\n   * @type {number}\n   */\n  get hour() {\n    return this.isValid ? this.c.hour : NaN;\n  }\n\n  /**\n   * Get the minute of the hour (0-59).\n   * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30\n   * @type {number}\n   */\n  get minute() {\n    return this.isValid ? this.c.minute : NaN;\n  }\n\n  /**\n   * Get the second of the minute (0-59).\n   * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52\n   * @type {number}\n   */\n  get second() {\n    return this.isValid ? this.c.second : NaN;\n  }\n\n  /**\n   * Get the millisecond of the second (0-999).\n   * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654\n   * @type {number}\n   */\n  get millisecond() {\n    return this.isValid ? this.c.millisecond : NaN;\n  }\n\n  /**\n   * Get the week year\n   * @see https://en.wikipedia.org/wiki/ISO_week_date\n   * @example DateTime.local(2014, 12, 31).weekYear //=> 2015\n   * @type {number}\n   */\n  get weekYear() {\n    return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;\n  }\n\n  /**\n   * Get the week number of the week year (1-52ish).\n   * @see https://en.wikipedia.org/wiki/ISO_week_date\n   * @example DateTime.local(2017, 5, 25).weekNumber //=> 21\n   * @type {number}\n   */\n  get weekNumber() {\n    return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;\n  }\n\n  /**\n   * Get the day of the week.\n   * 1 is Monday and 7 is Sunday\n   * @see https://en.wikipedia.org/wiki/ISO_week_date\n   * @example DateTime.local(2014, 11, 31).weekday //=> 4\n   * @type {number}\n   */\n  get weekday() {\n    return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;\n  }\n\n  /**\n   * Get the ordinal (meaning the day of the year)\n   * @example DateTime.local(2017, 5, 25).ordinal //=> 145\n   * @type {number|DateTime}\n   */\n  get ordinal() {\n    return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;\n  }\n\n  /**\n   * Get the human readable short month name, such as 'Oct'.\n   * Defaults to the system's locale if no locale has been specified\n   * @example DateTime.local(2017, 10, 30).monthShort //=> Oct\n   * @type {string}\n   */\n  get monthShort() {\n    return this.isValid ? Info.months(\"short\", { locObj: this.loc })[this.month - 1] : null;\n  }\n\n  /**\n   * Get the human readable long month name, such as 'October'.\n   * Defaults to the system's locale if no locale has been specified\n   * @example DateTime.local(2017, 10, 30).monthLong //=> October\n   * @type {string}\n   */\n  get monthLong() {\n    return this.isValid ? Info.months(\"long\", { locObj: this.loc })[this.month - 1] : null;\n  }\n\n  /**\n   * Get the human readable short weekday, such as 'Mon'.\n   * Defaults to the system's locale if no locale has been specified\n   * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon\n   * @type {string}\n   */\n  get weekdayShort() {\n    return this.isValid ? Info.weekdays(\"short\", { locObj: this.loc })[this.weekday - 1] : null;\n  }\n\n  /**\n   * Get the human readable long weekday, such as 'Monday'.\n   * Defaults to the system's locale if no locale has been specified\n   * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday\n   * @type {string}\n   */\n  get weekdayLong() {\n    return this.isValid ? Info.weekdays(\"long\", { locObj: this.loc })[this.weekday - 1] : null;\n  }\n\n  /**\n   * Get the UTC offset of this DateTime in minutes\n   * @example DateTime.now().offset //=> -240\n   * @example DateTime.utc().offset //=> 0\n   * @type {number}\n   */\n  get offset() {\n    return this.isValid ? +this.o : NaN;\n  }\n\n  /**\n   * Get the short human name for the zone's current offset, for example \"EST\" or \"EDT\".\n   * Defaults to the system's locale if no locale has been specified\n   * @type {string}\n   */\n  get offsetNameShort() {\n    if (this.isValid) {\n      return this.zone.offsetName(this.ts, {\n        format: \"short\",\n        locale: this.locale,\n      });\n    } else {\n      return null;\n    }\n  }\n\n  /**\n   * Get the long human name for the zone's current offset, for example \"Eastern Standard Time\" or \"Eastern Daylight Time\".\n   * Defaults to the system's locale if no locale has been specified\n   * @type {string}\n   */\n  get offsetNameLong() {\n    if (this.isValid) {\n      return this.zone.offsetName(this.ts, {\n        format: \"long\",\n        locale: this.locale,\n      });\n    } else {\n      return null;\n    }\n  }\n\n  /**\n   * Get whether this zone's offset ever changes, as in a DST.\n   * @type {boolean}\n   */\n  get isOffsetFixed() {\n    return this.isValid ? this.zone.isUniversal : null;\n  }\n\n  /**\n   * Get whether the DateTime is in a DST.\n   * @type {boolean}\n   */\n  get isInDST() {\n    if (this.isOffsetFixed) {\n      return false;\n    } else {\n      return (\n        this.offset > this.set({ month: 1, day: 1 }).offset ||\n        this.offset > this.set({ month: 5 }).offset\n      );\n    }\n  }\n\n  /**\n   * Returns true if this DateTime is in a leap year, false otherwise\n   * @example DateTime.local(2016).isInLeapYear //=> true\n   * @example DateTime.local(2013).isInLeapYear //=> false\n   * @type {boolean}\n   */\n  get isInLeapYear() {\n    return isLeapYear(this.year);\n  }\n\n  /**\n   * Returns the number of days in this DateTime's month\n   * @example DateTime.local(2016, 2).daysInMonth //=> 29\n   * @example DateTime.local(2016, 3).daysInMonth //=> 31\n   * @type {number}\n   */\n  get daysInMonth() {\n    return daysInMonth(this.year, this.month);\n  }\n\n  /**\n   * Returns the number of days in this DateTime's year\n   * @example DateTime.local(2016).daysInYear //=> 366\n   * @example DateTime.local(2013).daysInYear //=> 365\n   * @type {number}\n   */\n  get daysInYear() {\n    return this.isValid ? daysInYear(this.year) : NaN;\n  }\n\n  /**\n   * Returns the number of weeks in this DateTime's year\n   * @see https://en.wikipedia.org/wiki/ISO_week_date\n   * @example DateTime.local(2004).weeksInWeekYear //=> 53\n   * @example DateTime.local(2013).weeksInWeekYear //=> 52\n   * @type {number}\n   */\n  get weeksInWeekYear() {\n    return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;\n  }\n\n  /**\n   * Returns the resolved Intl options for this DateTime.\n   * This is useful in understanding the behavior of formatting methods\n   * @param {Object} opts - the same options as toLocaleString\n   * @return {Object}\n   */\n  resolvedLocaleOptions(opts = {}) {\n    const { locale, numberingSystem, calendar } = Formatter.create(\n      this.loc.clone(opts),\n      opts\n    ).resolvedOptions(this);\n    return { locale, numberingSystem, outputCalendar: calendar };\n  }\n\n  // TRANSFORM\n\n  /**\n   * \"Set\" the DateTime's zone to UTC. Returns a newly-constructed DateTime.\n   *\n   * Equivalent to {@link DateTime#setZone}('utc')\n   * @param {number} [offset=0] - optionally, an offset from UTC in minutes\n   * @param {Object} [opts={}] - options to pass to `setZone()`\n   * @return {DateTime}\n   */\n  toUTC(offset = 0, opts = {}) {\n    return this.setZone(FixedOffsetZone.instance(offset), opts);\n  }\n\n  /**\n   * \"Set\" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.\n   *\n   * Equivalent to `setZone('local')`\n   * @return {DateTime}\n   */\n  toLocal() {\n    return this.setZone(Settings.defaultZone);\n  }\n\n  /**\n   * \"Set\" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.\n   *\n   * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.\n   * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.\n   * @param {Object} opts - options\n   * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.\n   * @return {DateTime}\n   */\n  setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {\n    zone = normalizeZone(zone, Settings.defaultZone);\n    if (zone.equals(this.zone)) {\n      return this;\n    } else if (!zone.isValid) {\n      return DateTime.invalid(unsupportedZone(zone));\n    } else {\n      let newTS = this.ts;\n      if (keepLocalTime || keepCalendarTime) {\n        const offsetGuess = zone.offset(this.ts);\n        const asObj = this.toObject();\n        [newTS] = objToTS(asObj, offsetGuess, zone);\n      }\n      return clone(this, { ts: newTS, zone });\n    }\n  }\n\n  /**\n   * \"Set\" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.\n   * @param {Object} properties - the properties to set\n   * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })\n   * @return {DateTime}\n   */\n  reconfigure({ locale, numberingSystem, outputCalendar } = {}) {\n    const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });\n    return clone(this, { loc });\n  }\n\n  /**\n   * \"Set\" the locale. Returns a newly-constructed DateTime.\n   * Just a convenient alias for reconfigure({ locale })\n   * @example DateTime.local(2017, 5, 25).setLocale('en-GB')\n   * @return {DateTime}\n   */\n  setLocale(locale) {\n    return this.reconfigure({ locale });\n  }\n\n  /**\n   * \"Set\" the values of specified units. Returns a newly-constructed DateTime.\n   * You can only set units with this method; for \"setting\" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.\n   * @param {Object} values - a mapping of units to numbers\n   * @example dt.set({ year: 2017 })\n   * @example dt.set({ hour: 8, minute: 30 })\n   * @example dt.set({ weekday: 5 })\n   * @example dt.set({ year: 2005, ordinal: 234 })\n   * @return {DateTime}\n   */\n  set(values) {\n    if (!this.isValid) return this;\n\n    const normalized = normalizeObject(values, normalizeUnit),\n      settingWeekStuff =\n        !isUndefined(normalized.weekYear) ||\n        !isUndefined(normalized.weekNumber) ||\n        !isUndefined(normalized.weekday),\n      containsOrdinal = !isUndefined(normalized.ordinal),\n      containsGregorYear = !isUndefined(normalized.year),\n      containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n      containsGregor = containsGregorYear || containsGregorMD,\n      definiteWeekDef = normalized.weekYear || normalized.weekNumber;\n\n    if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n      throw new ConflictingSpecificationError(\n        \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n      );\n    }\n\n    if (containsGregorMD && containsOrdinal) {\n      throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n    }\n\n    let mixed;\n    if (settingWeekStuff) {\n      mixed = weekToGregorian({ ...gregorianToWeek(this.c), ...normalized });\n    } else if (!isUndefined(normalized.ordinal)) {\n      mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });\n    } else {\n      mixed = { ...this.toObject(), ...normalized };\n\n      // if we didn't set the day but we ended up on an overflow date,\n      // use the last day of the right month\n      if (isUndefined(normalized.day)) {\n        mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);\n      }\n    }\n\n    const [ts, o] = objToTS(mixed, this.o, this.zone);\n    return clone(this, { ts, o });\n  }\n\n  /**\n   * Add a period of time to this DateTime and return the resulting DateTime\n   *\n   * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.\n   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n   * @example DateTime.now().plus(123) //~> in 123 milliseconds\n   * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes\n   * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow\n   * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday\n   * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min\n   * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min\n   * @return {DateTime}\n   */\n  plus(duration) {\n    if (!this.isValid) return this;\n    const dur = Duration.fromDurationLike(duration);\n    return clone(this, adjustTime(this, dur));\n  }\n\n  /**\n   * Subtract a period of time to this DateTime and return the resulting DateTime\n   * See {@link DateTime#plus}\n   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n   @return {DateTime}\n   */\n  minus(duration) {\n    if (!this.isValid) return this;\n    const dur = Duration.fromDurationLike(duration).negate();\n    return clone(this, adjustTime(this, dur));\n  }\n\n  /**\n   * \"Set\" this DateTime to the beginning of a unit of time.\n   * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n   * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'\n   * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'\n   * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays\n   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'\n   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'\n   * @return {DateTime}\n   */\n  startOf(unit) {\n    if (!this.isValid) return this;\n    const o = {},\n      normalizedUnit = Duration.normalizeUnit(unit);\n    switch (normalizedUnit) {\n      case \"years\":\n        o.month = 1;\n      // falls through\n      case \"quarters\":\n      case \"months\":\n        o.day = 1;\n      // falls through\n      case \"weeks\":\n      case \"days\":\n        o.hour = 0;\n      // falls through\n      case \"hours\":\n        o.minute = 0;\n      // falls through\n      case \"minutes\":\n        o.second = 0;\n      // falls through\n      case \"seconds\":\n        o.millisecond = 0;\n        break;\n      case \"milliseconds\":\n        break;\n      // no default, invalid units throw in normalizeUnit()\n    }\n\n    if (normalizedUnit === \"weeks\") {\n      o.weekday = 1;\n    }\n\n    if (normalizedUnit === \"quarters\") {\n      const q = Math.ceil(this.month / 3);\n      o.month = (q - 1) * 3 + 1;\n    }\n\n    return this.set(o);\n  }\n\n  /**\n   * \"Set\" this DateTime to the end (meaning the last millisecond) of a unit of time\n   * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n   * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'\n   * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'\n   * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays\n   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'\n   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'\n   * @return {DateTime}\n   */\n  endOf(unit) {\n    return this.isValid\n      ? this.plus({ [unit]: 1 })\n          .startOf(unit)\n          .minus(1)\n      : this;\n  }\n\n  // OUTPUT\n\n  /**\n   * Returns a string representation of this DateTime formatted according to the specified format string.\n   * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).\n   * Defaults to en-US if no locale has been specified, regardless of the system's locale.\n   * @param {string} fmt - the format string\n   * @param {Object} opts - opts to override the configuration options on this DateTime\n   * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'\n   * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'\n   * @example DateTime.now().toFormat('yyyy LLL dd', { locale: \"fr\" }) //=> '2017 avr. 22'\n   * @example DateTime.now().toFormat(\"HH 'hours and' mm 'minutes'\") //=> '20 hours and 55 minutes'\n   * @return {string}\n   */\n  toFormat(fmt, opts = {}) {\n    return this.isValid\n      ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt)\n      : INVALID;\n  }\n\n  /**\n   * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.\n   * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation\n   * of the DateTime in the assigned locale.\n   * Defaults to the system's locale if no locale has been specified\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n   * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options\n   * @param {Object} opts - opts to override the configuration options on this DateTime\n   * @example DateTime.now().toLocaleString(); //=> 4/20/2017\n   * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'\n   * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'\n   * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'\n   * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'\n   * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'\n   * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'\n   * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'\n   * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'\n   * @return {string}\n   */\n  toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {\n    return this.isValid\n      ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this)\n      : INVALID;\n  }\n\n  /**\n   * Returns an array of format \"parts\", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.\n   * Defaults to the system's locale if no locale has been specified\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts\n   * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.\n   * @example DateTime.now().toLocaleParts(); //=> [\n   *                                   //=>   { type: 'day', value: '25' },\n   *                                   //=>   { type: 'literal', value: '/' },\n   *                                   //=>   { type: 'month', value: '05' },\n   *                                   //=>   { type: 'literal', value: '/' },\n   *                                   //=>   { type: 'year', value: '1982' }\n   *                                   //=> ]\n   */\n  toLocaleParts(opts = {}) {\n    return this.isValid\n      ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this)\n      : [];\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this DateTime\n   * @param {Object} opts - options\n   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n   * @param {boolean} [opts.extendedZone=false] - add the time zone format extension\n   * @param {string} [opts.format='extended'] - choose between the basic and extended format\n   * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'\n   * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'\n   * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'\n   * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'\n   * @return {string}\n   */\n  toISO({\n    format = \"extended\",\n    suppressSeconds = false,\n    suppressMilliseconds = false,\n    includeOffset = true,\n    extendedZone = false,\n  } = {}) {\n    if (!this.isValid) {\n      return null;\n    }\n\n    const ext = format === \"extended\";\n\n    let c = toISODate(this, ext);\n    c += \"T\";\n    c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);\n    return c;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this DateTime's date component\n   * @param {Object} opts - options\n   * @param {string} [opts.format='extended'] - choose between the basic and extended format\n   * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'\n   * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'\n   * @return {string}\n   */\n  toISODate({ format = \"extended\" } = {}) {\n    if (!this.isValid) {\n      return null;\n    }\n\n    return toISODate(this, format === \"extended\");\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this DateTime's week date\n   * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'\n   * @return {string}\n   */\n  toISOWeekDate() {\n    return toTechFormat(this, \"kkkk-'W'WW-c\");\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this DateTime's time component\n   * @param {Object} opts - options\n   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n   * @param {boolean} [opts.extendedZone=true] - add the time zone format extension\n   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n   * @param {string} [opts.format='extended'] - choose between the basic and extended format\n   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'\n   * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'\n   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'\n   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'\n   * @return {string}\n   */\n  toISOTime({\n    suppressMilliseconds = false,\n    suppressSeconds = false,\n    includeOffset = true,\n    includePrefix = false,\n    extendedZone = false,\n    format = \"extended\",\n  } = {}) {\n    if (!this.isValid) {\n      return null;\n    }\n\n    let c = includePrefix ? \"T\" : \"\";\n    return (\n      c +\n      toISOTime(\n        this,\n        format === \"extended\",\n        suppressSeconds,\n        suppressMilliseconds,\n        includeOffset,\n        extendedZone\n      )\n    );\n  }\n\n  /**\n   * Returns an RFC 2822-compatible string representation of this DateTime\n   * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'\n   * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'\n   * @return {string}\n   */\n  toRFC2822() {\n    return toTechFormat(this, \"EEE, dd LLL yyyy HH:mm:ss ZZZ\", false);\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.\n   * Specifically, the string conforms to RFC 1123.\n   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n   * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'\n   * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'\n   * @return {string}\n   */\n  toHTTP() {\n    return toTechFormat(this.toUTC(), \"EEE, dd LLL yyyy HH:mm:ss 'GMT'\");\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for use in SQL Date\n   * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'\n   * @return {string}\n   */\n  toSQLDate() {\n    if (!this.isValid) {\n      return null;\n    }\n    return toISODate(this, true);\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for use in SQL Time\n   * @param {Object} opts - options\n   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n   * @example DateTime.utc().toSQL() //=> '05:15:16.345'\n   * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'\n   * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'\n   * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'\n   * @return {string}\n   */\n  toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {\n    let fmt = \"HH:mm:ss.SSS\";\n\n    if (includeZone || includeOffset) {\n      if (includeOffsetSpace) {\n        fmt += \" \";\n      }\n      if (includeZone) {\n        fmt += \"z\";\n      } else if (includeOffset) {\n        fmt += \"ZZ\";\n      }\n    }\n\n    return toTechFormat(this, fmt, true);\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for use in SQL DateTime\n   * @param {Object} opts - options\n   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n   * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'\n   * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'\n   * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'\n   * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'\n   * @return {string}\n   */\n  toSQL(opts = {}) {\n    if (!this.isValid) {\n      return null;\n    }\n\n    return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for debugging\n   * @return {string}\n   */\n  toString() {\n    return this.isValid ? this.toISO() : INVALID;\n  }\n\n  /**\n   * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}\n   * @return {number}\n   */\n  valueOf() {\n    return this.toMillis();\n  }\n\n  /**\n   * Returns the epoch milliseconds of this DateTime.\n   * @return {number}\n   */\n  toMillis() {\n    return this.isValid ? this.ts : NaN;\n  }\n\n  /**\n   * Returns the epoch seconds of this DateTime.\n   * @return {number}\n   */\n  toSeconds() {\n    return this.isValid ? this.ts / 1000 : NaN;\n  }\n\n  /**\n   * Returns the epoch seconds (as a whole number) of this DateTime.\n   * @return {number}\n   */\n  toUnixInteger() {\n    return this.isValid ? Math.floor(this.ts / 1000) : NaN;\n  }\n\n  /**\n   * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.\n   * @return {string}\n   */\n  toJSON() {\n    return this.toISO();\n  }\n\n  /**\n   * Returns a BSON serializable equivalent to this DateTime.\n   * @return {Date}\n   */\n  toBSON() {\n    return this.toJSDate();\n  }\n\n  /**\n   * Returns a JavaScript object with this DateTime's year, month, day, and so on.\n   * @param opts - options for generating the object\n   * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output\n   * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }\n   * @return {Object}\n   */\n  toObject(opts = {}) {\n    if (!this.isValid) return {};\n\n    const base = { ...this.c };\n\n    if (opts.includeConfig) {\n      base.outputCalendar = this.outputCalendar;\n      base.numberingSystem = this.loc.numberingSystem;\n      base.locale = this.loc.locale;\n    }\n    return base;\n  }\n\n  /**\n   * Returns a JavaScript Date equivalent to this DateTime.\n   * @return {Date}\n   */\n  toJSDate() {\n    return new Date(this.isValid ? this.ts : NaN);\n  }\n\n  // COMPARE\n\n  /**\n   * Return the difference between two DateTimes as a Duration.\n   * @param {DateTime} otherDateTime - the DateTime to compare this one to\n   * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.\n   * @param {Object} opts - options that affect the creation of the Duration\n   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n   * @example\n   * var i1 = DateTime.fromISO('1982-05-25T09:45'),\n   *     i2 = DateTime.fromISO('1983-10-14T10:30');\n   * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }\n   * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }\n   * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }\n   * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }\n   * @return {Duration}\n   */\n  diff(otherDateTime, unit = \"milliseconds\", opts = {}) {\n    if (!this.isValid || !otherDateTime.isValid) {\n      return Duration.invalid(\"created by diffing an invalid DateTime\");\n    }\n\n    const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };\n\n    const units = maybeArray(unit).map(Duration.normalizeUnit),\n      otherIsLater = otherDateTime.valueOf() > this.valueOf(),\n      earlier = otherIsLater ? this : otherDateTime,\n      later = otherIsLater ? otherDateTime : this,\n      diffed = diff(earlier, later, units, durOpts);\n\n    return otherIsLater ? diffed.negate() : diffed;\n  }\n\n  /**\n   * Return the difference between this DateTime and right now.\n   * See {@link DateTime#diff}\n   * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration\n   * @param {Object} opts - options that affect the creation of the Duration\n   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n   * @return {Duration}\n   */\n  diffNow(unit = \"milliseconds\", opts = {}) {\n    return this.diff(DateTime.now(), unit, opts);\n  }\n\n  /**\n   * Return an Interval spanning between this DateTime and another DateTime\n   * @param {DateTime} otherDateTime - the other end point of the Interval\n   * @return {Interval}\n   */\n  until(otherDateTime) {\n    return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;\n  }\n\n  /**\n   * Return whether this DateTime is in the same unit of time as another DateTime.\n   * Higher-order units must also be identical for this function to return `true`.\n   * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.\n   * @param {DateTime} otherDateTime - the other DateTime\n   * @param {string} unit - the unit of time to check sameness on\n   * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day\n   * @return {boolean}\n   */\n  hasSame(otherDateTime, unit) {\n    if (!this.isValid) return false;\n\n    const inputMs = otherDateTime.valueOf();\n    const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });\n    return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit);\n  }\n\n  /**\n   * Equality check\n   * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.\n   * To compare just the millisecond values, use `+dt1 === +dt2`.\n   * @param {DateTime} other - the other DateTime\n   * @return {boolean}\n   */\n  equals(other) {\n    return (\n      this.isValid &&\n      other.isValid &&\n      this.valueOf() === other.valueOf() &&\n      this.zone.equals(other.zone) &&\n      this.loc.equals(other.loc)\n    );\n  }\n\n  /**\n   * Returns a string representation of a this time relative to now, such as \"in two days\". Can only internationalize if your\n   * platform supports Intl.RelativeTimeFormat. Rounds down by default.\n   * @param {Object} options - options that affect the output\n   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n   * @param {string} [options.style=\"long\"] - the style of units, must be \"long\", \"short\", or \"narrow\"\n   * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of \"years\", \"quarters\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", or \"seconds\"\n   * @param {boolean} [options.round=true] - whether to round the numbers in the output.\n   * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.\n   * @param {string} options.locale - override the locale of this DateTime\n   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n   * @example DateTime.now().plus({ days: 1 }).toRelative() //=> \"in 1 day\"\n   * @example DateTime.now().setLocale(\"es\").toRelative({ days: 1 }) //=> \"dentro de 1 día\"\n   * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: \"fr\" }) //=> \"dans 23 heures\"\n   * @example DateTime.now().minus({ days: 2 }).toRelative() //=> \"2 days ago\"\n   * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: \"hours\" }) //=> \"48 hours ago\"\n   * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> \"1.5 days ago\"\n   */\n  toRelative(options = {}) {\n    if (!this.isValid) return null;\n    const base = options.base || DateTime.fromObject({}, { zone: this.zone }),\n      padding = options.padding ? (this < base ? -options.padding : options.padding) : 0;\n    let units = [\"years\", \"months\", \"days\", \"hours\", \"minutes\", \"seconds\"];\n    let unit = options.unit;\n    if (Array.isArray(options.unit)) {\n      units = options.unit;\n      unit = undefined;\n    }\n    return diffRelative(base, this.plus(padding), {\n      ...options,\n      numeric: \"always\",\n      units,\n      unit,\n    });\n  }\n\n  /**\n   * Returns a string representation of this date relative to today, such as \"yesterday\" or \"next month\".\n   * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.\n   * @param {Object} options - options that affect the output\n   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n   * @param {string} options.locale - override the locale of this DateTime\n   * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of \"years\", \"quarters\", \"months\", \"weeks\", or \"days\"\n   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> \"tomorrow\"\n   * @example DateTime.now().setLocale(\"es\").plus({ days: 1 }).toRelative() //=> \"\"mañana\"\n   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: \"fr\" }) //=> \"demain\"\n   * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> \"2 days ago\"\n   */\n  toRelativeCalendar(options = {}) {\n    if (!this.isValid) return null;\n\n    return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, {\n      ...options,\n      numeric: \"auto\",\n      units: [\"years\", \"months\", \"days\"],\n      calendary: true,\n    });\n  }\n\n  /**\n   * Return the min of several date times\n   * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum\n   * @return {DateTime} the min DateTime, or undefined if called with no argument\n   */\n  static min(...dateTimes) {\n    if (!dateTimes.every(DateTime.isDateTime)) {\n      throw new InvalidArgumentError(\"min requires all arguments be DateTimes\");\n    }\n    return bestBy(dateTimes, (i) => i.valueOf(), Math.min);\n  }\n\n  /**\n   * Return the max of several date times\n   * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum\n   * @return {DateTime} the max DateTime, or undefined if called with no argument\n   */\n  static max(...dateTimes) {\n    if (!dateTimes.every(DateTime.isDateTime)) {\n      throw new InvalidArgumentError(\"max requires all arguments be DateTimes\");\n    }\n    return bestBy(dateTimes, (i) => i.valueOf(), Math.max);\n  }\n\n  // MISC\n\n  /**\n   * Explain how a string would be parsed by fromFormat()\n   * @param {string} text - the string to parse\n   * @param {string} fmt - the format the string is expected to be in (see description)\n   * @param {Object} options - options taken by fromFormat()\n   * @return {Object}\n   */\n  static fromFormatExplain(text, fmt, options = {}) {\n    const { locale = null, numberingSystem = null } = options,\n      localeToUse = Locale.fromOpts({\n        locale,\n        numberingSystem,\n        defaultToEN: true,\n      });\n    return explainFromTokens(localeToUse, text, fmt);\n  }\n\n  /**\n   * @deprecated use fromFormatExplain instead\n   */\n  static fromStringExplain(text, fmt, options = {}) {\n    return DateTime.fromFormatExplain(text, fmt, options);\n  }\n\n  // FORMAT PRESETS\n\n  /**\n   * {@link DateTime#toLocaleString} format like 10/14/1983\n   * @type {Object}\n   */\n  static get DATE_SHORT() {\n    return Formats.DATE_SHORT;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'\n   * @type {Object}\n   */\n  static get DATE_MED() {\n    return Formats.DATE_MED;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'\n   * @type {Object}\n   */\n  static get DATE_MED_WITH_WEEKDAY() {\n    return Formats.DATE_MED_WITH_WEEKDAY;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'October 14, 1983'\n   * @type {Object}\n   */\n  static get DATE_FULL() {\n    return Formats.DATE_FULL;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'\n   * @type {Object}\n   */\n  static get DATE_HUGE() {\n    return Formats.DATE_HUGE;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get TIME_SIMPLE() {\n    return Formats.TIME_SIMPLE;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get TIME_WITH_SECONDS() {\n    return Formats.TIME_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get TIME_WITH_SHORT_OFFSET() {\n    return Formats.TIME_WITH_SHORT_OFFSET;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get TIME_WITH_LONG_OFFSET() {\n    return Formats.TIME_WITH_LONG_OFFSET;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.\n   * @type {Object}\n   */\n  static get TIME_24_SIMPLE() {\n    return Formats.TIME_24_SIMPLE;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.\n   * @type {Object}\n   */\n  static get TIME_24_WITH_SECONDS() {\n    return Formats.TIME_24_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.\n   * @type {Object}\n   */\n  static get TIME_24_WITH_SHORT_OFFSET() {\n    return Formats.TIME_24_WITH_SHORT_OFFSET;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.\n   * @type {Object}\n   */\n  static get TIME_24_WITH_LONG_OFFSET() {\n    return Formats.TIME_24_WITH_LONG_OFFSET;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_SHORT() {\n    return Formats.DATETIME_SHORT;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_SHORT_WITH_SECONDS() {\n    return Formats.DATETIME_SHORT_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_MED() {\n    return Formats.DATETIME_MED;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_MED_WITH_SECONDS() {\n    return Formats.DATETIME_MED_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_MED_WITH_WEEKDAY() {\n    return Formats.DATETIME_MED_WITH_WEEKDAY;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_FULL() {\n    return Formats.DATETIME_FULL;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_FULL_WITH_SECONDS() {\n    return Formats.DATETIME_FULL_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_HUGE() {\n    return Formats.DATETIME_HUGE;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_HUGE_WITH_SECONDS() {\n    return Formats.DATETIME_HUGE_WITH_SECONDS;\n  }\n}\n\n/**\n * @private\n */\nexport function friendlyDateTime(dateTimeish) {\n  if (DateTime.isDateTime(dateTimeish)) {\n    return dateTimeish;\n  } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {\n    return DateTime.fromJSDate(dateTimeish);\n  } else if (dateTimeish && typeof dateTimeish === \"object\") {\n    return DateTime.fromObject(dateTimeish);\n  } else {\n    throw new InvalidArgumentError(\n      `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`\n    );\n  }\n}\n","import {DocumentReference, WriteBatch, writeBatch} from 'firebase/firestore';\n\nimport {FIRESTORE_STATE} from '../firebase/firestore_state';\n\ntype voidFn = () => void;\n\nexport class Batch {\n  private batch: WriteBatch;\n  private afterCommitFns: voidFn[] = [];\n\n  constructor() {\n    this.batch = writeBatch(FIRESTORE_STATE.store);\n  }\n\n  set<T>(ref: DocumentReference<T>, data: T) {\n    this.batch.set(ref, data);\n  }\n\n  delete<T>(ref: DocumentReference<T>) {\n    this.batch.delete(ref);\n  }\n\n  afterCommit(fn: voidFn) {\n    this.afterCommitFns.push(fn);\n  }\n\n  async commit(): Promise<void> {\n    await this.batch.commit();\n    for (const fn of this.afterCommitFns) {\n      fn();\n    }\n  }\n}\n","import {\n  DocumentData,\n  DocumentReference,\n  FirestoreDataConverter,\n  QueryDocumentSnapshot,\n  Timestamp,\n  collection,\n  getDocs,\n  orderBy,\n  query,\n} from 'firebase/firestore';\nimport {DateTime} from 'luxon';\n\nimport {FIRESTORE_STATE} from '../firebase/firestore_state';\n\nimport {Batch} from './batch';\nimport {INVITE_COLLECTION_ID, WORKSPACE_COLLECTION_ID} from './collections';\nimport {Entity} from './entity';\n\ninterface InviteFirestoreData {\n  email: string;\n  expiry: Timestamp;\n}\n\nexport class InviteError extends Error {}\nexport class InviteDataError extends InviteError {}\n\n// Note: Invites are functionally read-only except for deletion\nexport class Invite extends Entity<Invite> {\n  private _email: string;\n  private _expiry: DateTime;\n\n  private constructor(\n    ref: DocumentReference<Invite>,\n    dirty: boolean,\n    email: string,\n    expiry: DateTime,\n  ) {\n    super(ref, dirty);\n    this._email = email;\n    this._expiry = expiry;\n  }\n\n  get email(): string {\n    this.checkDeleted();\n    return this._email;\n  }\n\n  get expiry(): DateTime {\n    this.checkDeleted();\n    return this._expiry;\n  }\n\n  static async listForWorkspace(workspaceID: string): Promise<Invite[]> {\n    const q = query(\n      collection(FIRESTORE_STATE.store, WORKSPACE_COLLECTION_ID, workspaceID, INVITE_COLLECTION_ID),\n      orderBy('email'),\n    ).withConverter(INVITE_DATA_CONVERTER);\n    const invites = (await getDocs(q)).docs.map((doc) => doc.data());\n    const valid = [];\n    const expired = [];\n    for (const invite of invites) {\n      if (invite.expiry > DateTime.now()) {\n        valid.push(invite);\n      } else {\n        expired.push(invite);\n      }\n    }\n    if (expired.length > 0) {\n      const batch = new Batch();\n      for (const invite of expired) {\n        invite.deleteInBatch(batch);\n      }\n      batch.commit(); // Rely on eager evaluation.\n    }\n    return valid;\n  }\n\n  static fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData>): Invite {\n    return Invite.fromData(snapshot.ref, snapshot.data());\n  }\n\n  static fromData(ref: DocumentReference<unknown>, data: Partial<InviteFirestoreData>): Invite {\n    if (data.email == null) {\n      throw new InviteDataError('Firestore data for Invite has no email');\n    }\n    if (data.expiry == null) {\n      throw new InviteDataError('Firestore data for Invite has no expiry');\n    }\n    return new Invite(\n      ref.withConverter(INVITE_DATA_CONVERTER),\n      false,\n      data.email,\n      DateTime.fromMillis(data.expiry.toMillis(), {\n        zone: 'UTC',\n      }),\n    );\n  }\n\n  toFirestore(): InviteFirestoreData {\n    const data: InviteFirestoreData = {\n      email: this._email,\n      expiry: Timestamp.fromMillis(this._expiry.toMillis()),\n    };\n    return data;\n  }\n}\n\nexport const INVITE_DATA_CONVERTER: FirestoreDataConverter<Invite> = {\n  toFirestore: (i: Invite) => i.toFirestore(),\n  fromFirestore: (snapshot: QueryDocumentSnapshot<DocumentData>) => Invite.fromFirestore(snapshot),\n};\n","import {FirebaseApp} from 'firebase/app';\nimport {Timestamp, doc} from 'firebase/firestore';\nimport {\n  Functions,\n  HttpsCallable,\n  connectFunctionsEmulator,\n  getFunctions,\n  httpsCallable,\n} from 'firebase/functions';\n\nimport {INVITE_COLLECTION_ID, WORKSPACE_COLLECTION_ID} from '../data/collections';\nimport {Invite} from '../data/invite';\nimport {AugmentedWorkspace} from '../data/workspace';\nimport {assertDefined} from '../util/asserts';\n\nimport {FIRESTORE_STATE} from './firestore_state';\n\nconst DEV_BUILD = false;\n\ninterface InviteResponseData {\n  id: string;\n  expirySecs: number;\n  email: string;\n}\n\nexport class FunctionsState {\n  private functions?: Functions;\n  private _inviteToWorkspace?: HttpsCallable;\n  private _acceptInvite?: HttpsCallable;\n  private _rejectInvite?: HttpsCallable;\n\n  initialize(app: FirebaseApp) {\n    this.functions = getFunctions(app, 'europe-west1');\n    if (DEV_BUILD) {\n      connectFunctionsEmulator(this.functions, 'localhost', 5001);\n    }\n    this._inviteToWorkspace = httpsCallable(this.functions, 'invite_to_workspace');\n    this._acceptInvite = httpsCallable(this.functions, 'accept_invite');\n    this._rejectInvite = httpsCallable(this.functions, 'reject_invite');\n  }\n\n  async inviteToWorkspace(\n    workspace: AugmentedWorkspace,\n    targets: string[],\n    message: string | undefined,\n  ) {\n    const resp = await assertDefined(\n      this._inviteToWorkspace,\n      'invite_to_workspace callable',\n    )({\n      workspaceId: workspace.id,\n      targets,\n      message,\n    });\n\n    const invitesData = resp.data as Array<InviteResponseData>;\n\n    workspace.addInvites(\n      invitesData.map((invite) =>\n        Invite.fromData(\n          doc(\n            FIRESTORE_STATE.store,\n            WORKSPACE_COLLECTION_ID,\n            workspace.id,\n            INVITE_COLLECTION_ID,\n            assertDefined(invite.id, 'invite id'),\n          ),\n          {\n            expiry: Timestamp.fromMillis(invite.expirySecs * 1000),\n            email: invite.email,\n          },\n        ),\n      ),\n    );\n  }\n\n  async acceptInvite(workspaceId: string, inviteId: string): Promise<void> {\n    await assertDefined(this._acceptInvite, 'accept_invite callable')({workspaceId, inviteId});\n  }\n\n  async rejectInvite(workspaceId: string, inviteId: string): Promise<void> {\n    await assertDefined(this._rejectInvite, 'reject_invite callable')({workspaceId, inviteId});\n  }\n}\n\nexport const FUNCTIONS_STATE = new FunctionsState();\n","import { _getProvider, getApp, _registerComponent, registerVersion, SDK_VERSION } from '@firebase/app';\nimport { FirebaseError, isNode, createMockUserToken, getModularInstance, getDefaultEmulatorHostnameAndPort } from '@firebase/util';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Constants used in the Firebase Storage library.\r\n */\r\n/**\r\n * Domain name for firebase storage.\r\n */\r\nconst DEFAULT_HOST = 'firebasestorage.googleapis.com';\r\n/**\r\n * The key in Firebase config json for the storage bucket.\r\n */\r\nconst CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';\r\n/**\r\n * 2 minutes\r\n *\r\n * The timeout for all operations except upload.\r\n */\r\nconst DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;\r\n/**\r\n * 10 minutes\r\n *\r\n * The timeout for upload.\r\n */\r\nconst DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1000;\r\n/**\r\n * 1 second\r\n */\r\nconst DEFAULT_MIN_SLEEP_TIME_MILLIS = 1000;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An error returned by the Firebase Storage SDK.\r\n * @public\r\n */\r\nclass StorageError extends FirebaseError {\r\n    /**\r\n     * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and\r\n     *  added to the end of the message.\r\n     * @param message  - Error message.\r\n     * @param status_ - Corresponding HTTP Status Code\r\n     */\r\n    constructor(code, message, status_ = 0) {\r\n        super(prependCode(code), `Firebase Storage: ${message} (${prependCode(code)})`);\r\n        this.status_ = status_;\r\n        /**\r\n         * Stores custom error data unique to the `StorageError`.\r\n         */\r\n        this.customData = { serverResponse: null };\r\n        this._baseMessage = this.message;\r\n        // Without this, `instanceof StorageError`, in tests for example,\r\n        // returns false.\r\n        Object.setPrototypeOf(this, StorageError.prototype);\r\n    }\r\n    get status() {\r\n        return this.status_;\r\n    }\r\n    set status(status) {\r\n        this.status_ = status;\r\n    }\r\n    /**\r\n     * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.\r\n     */\r\n    _codeEquals(code) {\r\n        return prependCode(code) === this.code;\r\n    }\r\n    /**\r\n     * Optional response message that was added by the server.\r\n     */\r\n    get serverResponse() {\r\n        return this.customData.serverResponse;\r\n    }\r\n    set serverResponse(serverResponse) {\r\n        this.customData.serverResponse = serverResponse;\r\n        if (this.customData.serverResponse) {\r\n            this.message = `${this._baseMessage}\\n${this.customData.serverResponse}`;\r\n        }\r\n        else {\r\n            this.message = this._baseMessage;\r\n        }\r\n    }\r\n}\r\n/**\r\n * @public\r\n * Error codes that can be attached to `StorageError` objects.\r\n */\r\nvar StorageErrorCode;\r\n(function (StorageErrorCode) {\r\n    // Shared between all platforms\r\n    StorageErrorCode[\"UNKNOWN\"] = \"unknown\";\r\n    StorageErrorCode[\"OBJECT_NOT_FOUND\"] = \"object-not-found\";\r\n    StorageErrorCode[\"BUCKET_NOT_FOUND\"] = \"bucket-not-found\";\r\n    StorageErrorCode[\"PROJECT_NOT_FOUND\"] = \"project-not-found\";\r\n    StorageErrorCode[\"QUOTA_EXCEEDED\"] = \"quota-exceeded\";\r\n    StorageErrorCode[\"UNAUTHENTICATED\"] = \"unauthenticated\";\r\n    StorageErrorCode[\"UNAUTHORIZED\"] = \"unauthorized\";\r\n    StorageErrorCode[\"UNAUTHORIZED_APP\"] = \"unauthorized-app\";\r\n    StorageErrorCode[\"RETRY_LIMIT_EXCEEDED\"] = \"retry-limit-exceeded\";\r\n    StorageErrorCode[\"INVALID_CHECKSUM\"] = \"invalid-checksum\";\r\n    StorageErrorCode[\"CANCELED\"] = \"canceled\";\r\n    // JS specific\r\n    StorageErrorCode[\"INVALID_EVENT_NAME\"] = \"invalid-event-name\";\r\n    StorageErrorCode[\"INVALID_URL\"] = \"invalid-url\";\r\n    StorageErrorCode[\"INVALID_DEFAULT_BUCKET\"] = \"invalid-default-bucket\";\r\n    StorageErrorCode[\"NO_DEFAULT_BUCKET\"] = \"no-default-bucket\";\r\n    StorageErrorCode[\"CANNOT_SLICE_BLOB\"] = \"cannot-slice-blob\";\r\n    StorageErrorCode[\"SERVER_FILE_WRONG_SIZE\"] = \"server-file-wrong-size\";\r\n    StorageErrorCode[\"NO_DOWNLOAD_URL\"] = \"no-download-url\";\r\n    StorageErrorCode[\"INVALID_ARGUMENT\"] = \"invalid-argument\";\r\n    StorageErrorCode[\"INVALID_ARGUMENT_COUNT\"] = \"invalid-argument-count\";\r\n    StorageErrorCode[\"APP_DELETED\"] = \"app-deleted\";\r\n    StorageErrorCode[\"INVALID_ROOT_OPERATION\"] = \"invalid-root-operation\";\r\n    StorageErrorCode[\"INVALID_FORMAT\"] = \"invalid-format\";\r\n    StorageErrorCode[\"INTERNAL_ERROR\"] = \"internal-error\";\r\n    StorageErrorCode[\"UNSUPPORTED_ENVIRONMENT\"] = \"unsupported-environment\";\r\n})(StorageErrorCode || (StorageErrorCode = {}));\r\nfunction prependCode(code) {\r\n    return 'storage/' + code;\r\n}\r\nfunction unknown() {\r\n    const message = 'An unknown error occurred, please check the error payload for ' +\r\n        'server response.';\r\n    return new StorageError(StorageErrorCode.UNKNOWN, message);\r\n}\r\nfunction objectNotFound(path) {\r\n    return new StorageError(StorageErrorCode.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\r\n}\r\nfunction quotaExceeded(bucket) {\r\n    return new StorageError(StorageErrorCode.QUOTA_EXCEEDED, \"Quota for bucket '\" +\r\n        bucket +\r\n        \"' exceeded, please view quota on \" +\r\n        'https://firebase.google.com/pricing/.');\r\n}\r\nfunction unauthenticated() {\r\n    const message = 'User is not authenticated, please authenticate using Firebase ' +\r\n        'Authentication and try again.';\r\n    return new StorageError(StorageErrorCode.UNAUTHENTICATED, message);\r\n}\r\nfunction unauthorizedApp() {\r\n    return new StorageError(StorageErrorCode.UNAUTHORIZED_APP, 'This app does not have permission to access Firebase Storage on this project.');\r\n}\r\nfunction unauthorized(path) {\r\n    return new StorageError(StorageErrorCode.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\r\n}\r\nfunction retryLimitExceeded() {\r\n    return new StorageError(StorageErrorCode.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\r\n}\r\nfunction canceled() {\r\n    return new StorageError(StorageErrorCode.CANCELED, 'User canceled the upload/download.');\r\n}\r\nfunction invalidUrl(url) {\r\n    return new StorageError(StorageErrorCode.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\r\n}\r\nfunction invalidDefaultBucket(bucket) {\r\n    return new StorageError(StorageErrorCode.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\r\n}\r\nfunction noDefaultBucket() {\r\n    return new StorageError(StorageErrorCode.NO_DEFAULT_BUCKET, 'No default bucket ' +\r\n        \"found. Did you set the '\" +\r\n        CONFIG_STORAGE_BUCKET_KEY +\r\n        \"' property when initializing the app?\");\r\n}\r\nfunction cannotSliceBlob() {\r\n    return new StorageError(StorageErrorCode.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\r\n}\r\nfunction serverFileWrongSize() {\r\n    return new StorageError(StorageErrorCode.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\r\n}\r\nfunction noDownloadURL() {\r\n    return new StorageError(StorageErrorCode.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\r\n}\r\nfunction missingPolyFill(polyFill) {\r\n    return new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, `${polyFill} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`);\r\n}\r\n/**\r\n * @internal\r\n */\r\nfunction invalidArgument(message) {\r\n    return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);\r\n}\r\nfunction appDeleted() {\r\n    return new StorageError(StorageErrorCode.APP_DELETED, 'The Firebase app was deleted.');\r\n}\r\n/**\r\n * @param name - The name of the operation that was invalid.\r\n *\r\n * @internal\r\n */\r\nfunction invalidRootOperation(name) {\r\n    return new StorageError(StorageErrorCode.INVALID_ROOT_OPERATION, \"The operation '\" +\r\n        name +\r\n        \"' cannot be performed on a root reference, create a non-root \" +\r\n        \"reference using child, such as .child('file.png').\");\r\n}\r\n/**\r\n * @param format - The format that was not valid.\r\n * @param message - A message describing the format violation.\r\n */\r\nfunction invalidFormat(format, message) {\r\n    return new StorageError(StorageErrorCode.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\r\n}\r\n/**\r\n * @param message - A message describing the internal error.\r\n */\r\nfunction internalError(message) {\r\n    throw new StorageError(StorageErrorCode.INTERNAL_ERROR, 'Internal error: ' + message);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Firebase Storage location data.\r\n *\r\n * @internal\r\n */\r\nclass Location {\r\n    constructor(bucket, path) {\r\n        this.bucket = bucket;\r\n        this.path_ = path;\r\n    }\r\n    get path() {\r\n        return this.path_;\r\n    }\r\n    get isRoot() {\r\n        return this.path.length === 0;\r\n    }\r\n    fullServerUrl() {\r\n        const encode = encodeURIComponent;\r\n        return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\r\n    }\r\n    bucketOnlyServerUrl() {\r\n        const encode = encodeURIComponent;\r\n        return '/b/' + encode(this.bucket) + '/o';\r\n    }\r\n    static makeFromBucketSpec(bucketString, host) {\r\n        let bucketLocation;\r\n        try {\r\n            bucketLocation = Location.makeFromUrl(bucketString, host);\r\n        }\r\n        catch (e) {\r\n            // Not valid URL, use as-is. This lets you put bare bucket names in\r\n            // config.\r\n            return new Location(bucketString, '');\r\n        }\r\n        if (bucketLocation.path === '') {\r\n            return bucketLocation;\r\n        }\r\n        else {\r\n            throw invalidDefaultBucket(bucketString);\r\n        }\r\n    }\r\n    static makeFromUrl(url, host) {\r\n        let location = null;\r\n        const bucketDomain = '([A-Za-z0-9.\\\\-_]+)';\r\n        function gsModify(loc) {\r\n            if (loc.path.charAt(loc.path.length - 1) === '/') {\r\n                loc.path_ = loc.path_.slice(0, -1);\r\n            }\r\n        }\r\n        const gsPath = '(/(.*))?$';\r\n        const gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\r\n        const gsIndices = { bucket: 1, path: 3 };\r\n        function httpModify(loc) {\r\n            loc.path_ = decodeURIComponent(loc.path);\r\n        }\r\n        const version = 'v[A-Za-z0-9_]+';\r\n        const firebaseStorageHost = host.replace(/[.]/g, '\\\\.');\r\n        const firebaseStoragePath = '(/([^?#]*).*)?$';\r\n        const firebaseStorageRegExp = new RegExp(`^https?://${firebaseStorageHost}/${version}/b/${bucketDomain}/o${firebaseStoragePath}`, 'i');\r\n        const firebaseStorageIndices = { bucket: 1, path: 3 };\r\n        const cloudStorageHost = host === DEFAULT_HOST\r\n            ? '(?:storage.googleapis.com|storage.cloud.google.com)'\r\n            : host;\r\n        const cloudStoragePath = '([^?#]*)';\r\n        const cloudStorageRegExp = new RegExp(`^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`, 'i');\r\n        const cloudStorageIndices = { bucket: 1, path: 2 };\r\n        const groups = [\r\n            { regex: gsRegex, indices: gsIndices, postModify: gsModify },\r\n            {\r\n                regex: firebaseStorageRegExp,\r\n                indices: firebaseStorageIndices,\r\n                postModify: httpModify\r\n            },\r\n            {\r\n                regex: cloudStorageRegExp,\r\n                indices: cloudStorageIndices,\r\n                postModify: httpModify\r\n            }\r\n        ];\r\n        for (let i = 0; i < groups.length; i++) {\r\n            const group = groups[i];\r\n            const captures = group.regex.exec(url);\r\n            if (captures) {\r\n                const bucketValue = captures[group.indices.bucket];\r\n                let pathValue = captures[group.indices.path];\r\n                if (!pathValue) {\r\n                    pathValue = '';\r\n                }\r\n                location = new Location(bucketValue, pathValue);\r\n                group.postModify(location);\r\n                break;\r\n            }\r\n        }\r\n        if (location == null) {\r\n            throw invalidUrl(url);\r\n        }\r\n        return location;\r\n    }\r\n}\n\n/**\r\n * A request whose promise always fails.\r\n */\r\nclass FailRequest {\r\n    constructor(error) {\r\n        this.promise_ = Promise.reject(error);\r\n    }\r\n    /** @inheritDoc */\r\n    getPromise() {\r\n        return this.promise_;\r\n    }\r\n    /** @inheritDoc */\r\n    cancel(_appDelete = false) { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Accepts a callback for an action to perform (`doRequest`),\r\n * and then a callback for when the backoff has completed (`backoffCompleteCb`).\r\n * The callback sent to start requires an argument to call (`onRequestComplete`).\r\n * When `start` calls `doRequest`, it passes a callback for when the request has\r\n * completed, `onRequestComplete`. Based on this, the backoff continues, with\r\n * another call to `doRequest` and the above loop continues until the timeout\r\n * is hit, or a successful response occurs.\r\n * @description\r\n * @param doRequest Callback to perform request\r\n * @param backoffCompleteCb Callback to call when backoff has been completed\r\n */\r\nfunction start(doRequest, \r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nbackoffCompleteCb, timeout) {\r\n    // TODO(andysoto): make this code cleaner (probably refactor into an actual\r\n    // type instead of a bunch of functions with state shared in the closure)\r\n    let waitSeconds = 1;\r\n    // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\r\n    // TODO: find a way to exclude Node type definition for storage because storage only works in browser\r\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n    let retryTimeoutId = null;\r\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n    let globalTimeoutId = null;\r\n    let hitTimeout = false;\r\n    let cancelState = 0;\r\n    function canceled() {\r\n        return cancelState === 2;\r\n    }\r\n    let triggeredCallback = false;\r\n    function triggerCallback(...args) {\r\n        if (!triggeredCallback) {\r\n            triggeredCallback = true;\r\n            backoffCompleteCb.apply(null, args);\r\n        }\r\n    }\r\n    function callWithDelay(millis) {\r\n        retryTimeoutId = setTimeout(() => {\r\n            retryTimeoutId = null;\r\n            doRequest(responseHandler, canceled());\r\n        }, millis);\r\n    }\r\n    function clearGlobalTimeout() {\r\n        if (globalTimeoutId) {\r\n            clearTimeout(globalTimeoutId);\r\n        }\r\n    }\r\n    function responseHandler(success, ...args) {\r\n        if (triggeredCallback) {\r\n            clearGlobalTimeout();\r\n            return;\r\n        }\r\n        if (success) {\r\n            clearGlobalTimeout();\r\n            triggerCallback.call(null, success, ...args);\r\n            return;\r\n        }\r\n        const mustStop = canceled() || hitTimeout;\r\n        if (mustStop) {\r\n            clearGlobalTimeout();\r\n            triggerCallback.call(null, success, ...args);\r\n            return;\r\n        }\r\n        if (waitSeconds < 64) {\r\n            /* TODO(andysoto): don't back off so quickly if we know we're offline. */\r\n            waitSeconds *= 2;\r\n        }\r\n        let waitMillis;\r\n        if (cancelState === 1) {\r\n            cancelState = 2;\r\n            waitMillis = 0;\r\n        }\r\n        else {\r\n            waitMillis = (waitSeconds + Math.random()) * 1000;\r\n        }\r\n        callWithDelay(waitMillis);\r\n    }\r\n    let stopped = false;\r\n    function stop(wasTimeout) {\r\n        if (stopped) {\r\n            return;\r\n        }\r\n        stopped = true;\r\n        clearGlobalTimeout();\r\n        if (triggeredCallback) {\r\n            return;\r\n        }\r\n        if (retryTimeoutId !== null) {\r\n            if (!wasTimeout) {\r\n                cancelState = 2;\r\n            }\r\n            clearTimeout(retryTimeoutId);\r\n            callWithDelay(0);\r\n        }\r\n        else {\r\n            if (!wasTimeout) {\r\n                cancelState = 1;\r\n            }\r\n        }\r\n    }\r\n    callWithDelay(0);\r\n    globalTimeoutId = setTimeout(() => {\r\n        hitTimeout = true;\r\n        stop(true);\r\n    }, timeout);\r\n    return stop;\r\n}\r\n/**\r\n * Stops the retry loop from repeating.\r\n * If the function is currently \"in between\" retries, it is invoked immediately\r\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\r\n * after the current invocation finishes iff the current invocation would have\r\n * triggered another retry.\r\n */\r\nfunction stop(id) {\r\n    id(false);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isJustDef(p) {\r\n    return p !== void 0;\r\n}\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction isFunction(p) {\r\n    return typeof p === 'function';\r\n}\r\nfunction isNonArrayObject(p) {\r\n    return typeof p === 'object' && !Array.isArray(p);\r\n}\r\nfunction isString(p) {\r\n    return typeof p === 'string' || p instanceof String;\r\n}\r\nfunction isNativeBlob(p) {\r\n    return isNativeBlobDefined() && p instanceof Blob;\r\n}\r\nfunction isNativeBlobDefined() {\r\n    // Note: The `isNode()` check can be removed when `node-fetch` adds native Blob support\r\n    // PR: https://github.com/node-fetch/node-fetch/pull/1664\r\n    return typeof Blob !== 'undefined' && !isNode();\r\n}\r\nfunction validateNumber(argument, minValue, maxValue, value) {\r\n    if (value < minValue) {\r\n        throw invalidArgument(`Invalid value for '${argument}'. Expected ${minValue} or greater.`);\r\n    }\r\n    if (value > maxValue) {\r\n        throw invalidArgument(`Invalid value for '${argument}'. Expected ${maxValue} or less.`);\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction makeUrl(urlPart, host, protocol) {\r\n    let origin = host;\r\n    if (protocol == null) {\r\n        origin = `https://${host}`;\r\n    }\r\n    return `${protocol}://${origin}/v0${urlPart}`;\r\n}\r\nfunction makeQueryString(params) {\r\n    const encode = encodeURIComponent;\r\n    let queryPart = '?';\r\n    for (const key in params) {\r\n        if (params.hasOwnProperty(key)) {\r\n            const nextPart = encode(key) + '=' + encode(params[key]);\r\n            queryPart = queryPart + nextPart + '&';\r\n        }\r\n    }\r\n    // Chop off the extra '&' or '?' on the end\r\n    queryPart = queryPart.slice(0, -1);\r\n    return queryPart;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Error codes for requests made by the the XhrIo wrapper.\r\n */\r\nvar ErrorCode;\r\n(function (ErrorCode) {\r\n    ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\r\n    ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\r\n    ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\r\n})(ErrorCode || (ErrorCode = {}));\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Checks the status code to see if the action should be retried.\r\n *\r\n * @param status Current HTTP status code returned by server.\r\n * @param additionalRetryCodes additional retry codes to check against\r\n */\r\nfunction isRetryStatusCode(status, additionalRetryCodes) {\r\n    // The codes for which to retry came from this page:\r\n    // https://cloud.google.com/storage/docs/exponential-backoff\r\n    const isFiveHundredCode = status >= 500 && status < 600;\r\n    const extraRetryCodes = [\r\n        // Request Timeout: web server didn't receive full request in time.\r\n        408,\r\n        // Too Many Requests: you're getting rate-limited, basically.\r\n        429\r\n    ];\r\n    const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;\r\n    const isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;\r\n    return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Handles network logic for all Storage Requests, including error reporting and\r\n * retries with backoff.\r\n *\r\n * @param I - the type of the backend's network response.\r\n * @param - O the output type used by the rest of the SDK. The conversion\r\n * happens in the specified `callback_`.\r\n */\r\nclass NetworkRequest {\r\n    constructor(url_, method_, headers_, body_, successCodes_, additionalRetryCodes_, callback_, errorCallback_, timeout_, progressCallback_, connectionFactory_, retry = true) {\r\n        this.url_ = url_;\r\n        this.method_ = method_;\r\n        this.headers_ = headers_;\r\n        this.body_ = body_;\r\n        this.successCodes_ = successCodes_;\r\n        this.additionalRetryCodes_ = additionalRetryCodes_;\r\n        this.callback_ = callback_;\r\n        this.errorCallback_ = errorCallback_;\r\n        this.timeout_ = timeout_;\r\n        this.progressCallback_ = progressCallback_;\r\n        this.connectionFactory_ = connectionFactory_;\r\n        this.retry = retry;\r\n        this.pendingConnection_ = null;\r\n        this.backoffId_ = null;\r\n        this.canceled_ = false;\r\n        this.appDelete_ = false;\r\n        this.promise_ = new Promise((resolve, reject) => {\r\n            this.resolve_ = resolve;\r\n            this.reject_ = reject;\r\n            this.start_();\r\n        });\r\n    }\r\n    /**\r\n     * Actually starts the retry loop.\r\n     */\r\n    start_() {\r\n        const doTheRequest = (backoffCallback, canceled) => {\r\n            if (canceled) {\r\n                backoffCallback(false, new RequestEndStatus(false, null, true));\r\n                return;\r\n            }\r\n            const connection = this.connectionFactory_();\r\n            this.pendingConnection_ = connection;\r\n            const progressListener = progressEvent => {\r\n                const loaded = progressEvent.loaded;\r\n                const total = progressEvent.lengthComputable ? progressEvent.total : -1;\r\n                if (this.progressCallback_ !== null) {\r\n                    this.progressCallback_(loaded, total);\r\n                }\r\n            };\r\n            if (this.progressCallback_ !== null) {\r\n                connection.addUploadProgressListener(progressListener);\r\n            }\r\n            // connection.send() never rejects, so we don't need to have a error handler or use catch on the returned promise.\r\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n            connection\r\n                .send(this.url_, this.method_, this.body_, this.headers_)\r\n                .then(() => {\r\n                if (this.progressCallback_ !== null) {\r\n                    connection.removeUploadProgressListener(progressListener);\r\n                }\r\n                this.pendingConnection_ = null;\r\n                const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;\r\n                const status = connection.getStatus();\r\n                if (!hitServer ||\r\n                    (isRetryStatusCode(status, this.additionalRetryCodes_) &&\r\n                        this.retry)) {\r\n                    const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;\r\n                    backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\r\n                    return;\r\n                }\r\n                const successCode = this.successCodes_.indexOf(status) !== -1;\r\n                backoffCallback(true, new RequestEndStatus(successCode, connection));\r\n            });\r\n        };\r\n        /**\r\n         * @param requestWentThrough - True if the request eventually went\r\n         *     through, false if it hit the retry limit or was canceled.\r\n         */\r\n        const backoffDone = (requestWentThrough, status) => {\r\n            const resolve = this.resolve_;\r\n            const reject = this.reject_;\r\n            const connection = status.connection;\r\n            if (status.wasSuccessCode) {\r\n                try {\r\n                    const result = this.callback_(connection, connection.getResponse());\r\n                    if (isJustDef(result)) {\r\n                        resolve(result);\r\n                    }\r\n                    else {\r\n                        resolve();\r\n                    }\r\n                }\r\n                catch (e) {\r\n                    reject(e);\r\n                }\r\n            }\r\n            else {\r\n                if (connection !== null) {\r\n                    const err = unknown();\r\n                    err.serverResponse = connection.getErrorText();\r\n                    if (this.errorCallback_) {\r\n                        reject(this.errorCallback_(connection, err));\r\n                    }\r\n                    else {\r\n                        reject(err);\r\n                    }\r\n                }\r\n                else {\r\n                    if (status.canceled) {\r\n                        const err = this.appDelete_ ? appDeleted() : canceled();\r\n                        reject(err);\r\n                    }\r\n                    else {\r\n                        const err = retryLimitExceeded();\r\n                        reject(err);\r\n                    }\r\n                }\r\n            }\r\n        };\r\n        if (this.canceled_) {\r\n            backoffDone(false, new RequestEndStatus(false, null, true));\r\n        }\r\n        else {\r\n            this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\r\n        }\r\n    }\r\n    /** @inheritDoc */\r\n    getPromise() {\r\n        return this.promise_;\r\n    }\r\n    /** @inheritDoc */\r\n    cancel(appDelete) {\r\n        this.canceled_ = true;\r\n        this.appDelete_ = appDelete || false;\r\n        if (this.backoffId_ !== null) {\r\n            stop(this.backoffId_);\r\n        }\r\n        if (this.pendingConnection_ !== null) {\r\n            this.pendingConnection_.abort();\r\n        }\r\n    }\r\n}\r\n/**\r\n * A collection of information about the result of a network request.\r\n * @param opt_canceled - Defaults to false.\r\n */\r\nclass RequestEndStatus {\r\n    constructor(wasSuccessCode, connection, canceled) {\r\n        this.wasSuccessCode = wasSuccessCode;\r\n        this.connection = connection;\r\n        this.canceled = !!canceled;\r\n    }\r\n}\r\nfunction addAuthHeader_(headers, authToken) {\r\n    if (authToken !== null && authToken.length > 0) {\r\n        headers['Authorization'] = 'Firebase ' + authToken;\r\n    }\r\n}\r\nfunction addVersionHeader_(headers, firebaseVersion) {\r\n    headers['X-Firebase-Storage-Version'] =\r\n        'webjs/' + (firebaseVersion !== null && firebaseVersion !== void 0 ? firebaseVersion : 'AppManager');\r\n}\r\nfunction addGmpidHeader_(headers, appId) {\r\n    if (appId) {\r\n        headers['X-Firebase-GMPID'] = appId;\r\n    }\r\n}\r\nfunction addAppCheckHeader_(headers, appCheckToken) {\r\n    if (appCheckToken !== null) {\r\n        headers['X-Firebase-AppCheck'] = appCheckToken;\r\n    }\r\n}\r\nfunction makeRequest(requestInfo, appId, authToken, appCheckToken, requestFactory, firebaseVersion, retry = true) {\r\n    const queryPart = makeQueryString(requestInfo.urlParams);\r\n    const url = requestInfo.url + queryPart;\r\n    const headers = Object.assign({}, requestInfo.headers);\r\n    addGmpidHeader_(headers, appId);\r\n    addAuthHeader_(headers, authToken);\r\n    addVersionHeader_(headers, firebaseVersion);\r\n    addAppCheckHeader_(headers, appCheckToken);\r\n    return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, requestFactory, retry);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getBlobBuilder() {\r\n    if (typeof BlobBuilder !== 'undefined') {\r\n        return BlobBuilder;\r\n    }\r\n    else if (typeof WebKitBlobBuilder !== 'undefined') {\r\n        return WebKitBlobBuilder;\r\n    }\r\n    else {\r\n        return undefined;\r\n    }\r\n}\r\n/**\r\n * Concatenates one or more values together and converts them to a Blob.\r\n *\r\n * @param args The values that will make up the resulting blob.\r\n * @return The blob.\r\n */\r\nfunction getBlob$1(...args) {\r\n    const BlobBuilder = getBlobBuilder();\r\n    if (BlobBuilder !== undefined) {\r\n        const bb = new BlobBuilder();\r\n        for (let i = 0; i < args.length; i++) {\r\n            bb.append(args[i]);\r\n        }\r\n        return bb.getBlob();\r\n    }\r\n    else {\r\n        if (isNativeBlobDefined()) {\r\n            return new Blob(args);\r\n        }\r\n        else {\r\n            throw new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, \"This browser doesn't seem to support creating Blobs\");\r\n        }\r\n    }\r\n}\r\n/**\r\n * Slices the blob. The returned blob contains data from the start byte\r\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\r\n *\r\n * @param blob The blob to be sliced.\r\n * @param start Index of the starting byte.\r\n * @param end Index of the ending byte.\r\n * @return The blob slice or null if not supported.\r\n */\r\nfunction sliceBlob(blob, start, end) {\r\n    if (blob.webkitSlice) {\r\n        return blob.webkitSlice(start, end);\r\n    }\r\n    else if (blob.mozSlice) {\r\n        return blob.mozSlice(start, end);\r\n    }\r\n    else if (blob.slice) {\r\n        return blob.slice(start, end);\r\n    }\r\n    return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Converts a Base64 encoded string to a binary string. */\r\nfunction decodeBase64(encoded) {\r\n    if (typeof atob === 'undefined') {\r\n        throw missingPolyFill('base-64');\r\n    }\r\n    return atob(encoded);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An enumeration of the possible string formats for upload.\r\n * @public\r\n */\r\nconst StringFormat = {\r\n    /**\r\n     * Indicates the string should be interpreted \"raw\", that is, as normal text.\r\n     * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte\r\n     * sequence.\r\n     * Example: The string 'Hello! \\\\ud83d\\\\ude0a' becomes the byte sequence\r\n     * 48 65 6c 6c 6f 21 20 f0 9f 98 8a\r\n     */\r\n    RAW: 'raw',\r\n    /**\r\n     * Indicates the string should be interpreted as base64-encoded data.\r\n     * Padding characters (trailing '='s) are optional.\r\n     * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence\r\n     * ad 69 8e fb e1 3a b7 bf eb 97\r\n     */\r\n    BASE64: 'base64',\r\n    /**\r\n     * Indicates the string should be interpreted as base64url-encoded data.\r\n     * Padding characters (trailing '='s) are optional.\r\n     * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence\r\n     * ad 69 8e fb e1 3a b7 bf eb 97\r\n     */\r\n    BASE64URL: 'base64url',\r\n    /**\r\n     * Indicates the string is a data URL, such as one obtained from\r\n     * canvas.toDataURL().\r\n     * Example: the string 'data:application/octet-stream;base64,aaaa'\r\n     * becomes the byte sequence\r\n     * 69 a6 9a\r\n     * (the content-type \"application/octet-stream\" is also applied, but can\r\n     * be overridden in the metadata object).\r\n     */\r\n    DATA_URL: 'data_url'\r\n};\r\nclass StringData {\r\n    constructor(data, contentType) {\r\n        this.data = data;\r\n        this.contentType = contentType || null;\r\n    }\r\n}\r\n/**\r\n * @internal\r\n */\r\nfunction dataFromString(format, stringData) {\r\n    switch (format) {\r\n        case StringFormat.RAW:\r\n            return new StringData(utf8Bytes_(stringData));\r\n        case StringFormat.BASE64:\r\n        case StringFormat.BASE64URL:\r\n            return new StringData(base64Bytes_(format, stringData));\r\n        case StringFormat.DATA_URL:\r\n            return new StringData(dataURLBytes_(stringData), dataURLContentType_(stringData));\r\n        // do nothing\r\n    }\r\n    // assert(false);\r\n    throw unknown();\r\n}\r\nfunction utf8Bytes_(value) {\r\n    const b = [];\r\n    for (let i = 0; i < value.length; i++) {\r\n        let c = value.charCodeAt(i);\r\n        if (c <= 127) {\r\n            b.push(c);\r\n        }\r\n        else {\r\n            if (c <= 2047) {\r\n                b.push(192 | (c >> 6), 128 | (c & 63));\r\n            }\r\n            else {\r\n                if ((c & 64512) === 55296) {\r\n                    // The start of a surrogate pair.\r\n                    const valid = i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;\r\n                    if (!valid) {\r\n                        // The second surrogate wasn't there.\r\n                        b.push(239, 191, 189);\r\n                    }\r\n                    else {\r\n                        const hi = c;\r\n                        const lo = value.charCodeAt(++i);\r\n                        c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\r\n                        b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\r\n                    }\r\n                }\r\n                else {\r\n                    if ((c & 64512) === 56320) {\r\n                        // Invalid low surrogate.\r\n                        b.push(239, 191, 189);\r\n                    }\r\n                    else {\r\n                        b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n    return new Uint8Array(b);\r\n}\r\nfunction percentEncodedBytes_(value) {\r\n    let decoded;\r\n    try {\r\n        decoded = decodeURIComponent(value);\r\n    }\r\n    catch (e) {\r\n        throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\r\n    }\r\n    return utf8Bytes_(decoded);\r\n}\r\nfunction base64Bytes_(format, value) {\r\n    switch (format) {\r\n        case StringFormat.BASE64: {\r\n            const hasMinus = value.indexOf('-') !== -1;\r\n            const hasUnder = value.indexOf('_') !== -1;\r\n            if (hasMinus || hasUnder) {\r\n                const invalidChar = hasMinus ? '-' : '_';\r\n                throw invalidFormat(format, \"Invalid character '\" +\r\n                    invalidChar +\r\n                    \"' found: is it base64url encoded?\");\r\n            }\r\n            break;\r\n        }\r\n        case StringFormat.BASE64URL: {\r\n            const hasPlus = value.indexOf('+') !== -1;\r\n            const hasSlash = value.indexOf('/') !== -1;\r\n            if (hasPlus || hasSlash) {\r\n                const invalidChar = hasPlus ? '+' : '/';\r\n                throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\r\n            }\r\n            value = value.replace(/-/g, '+').replace(/_/g, '/');\r\n            break;\r\n        }\r\n        // do nothing\r\n    }\r\n    let bytes;\r\n    try {\r\n        bytes = decodeBase64(value);\r\n    }\r\n    catch (e) {\r\n        if (e.message.includes('polyfill')) {\r\n            throw e;\r\n        }\r\n        throw invalidFormat(format, 'Invalid character found');\r\n    }\r\n    const array = new Uint8Array(bytes.length);\r\n    for (let i = 0; i < bytes.length; i++) {\r\n        array[i] = bytes.charCodeAt(i);\r\n    }\r\n    return array;\r\n}\r\nclass DataURLParts {\r\n    constructor(dataURL) {\r\n        this.base64 = false;\r\n        this.contentType = null;\r\n        const matches = dataURL.match(/^data:([^,]+)?,/);\r\n        if (matches === null) {\r\n            throw invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[<mediatype>][;base64],<data>\");\r\n        }\r\n        const middle = matches[1] || null;\r\n        if (middle != null) {\r\n            this.base64 = endsWith(middle, ';base64');\r\n            this.contentType = this.base64\r\n                ? middle.substring(0, middle.length - ';base64'.length)\r\n                : middle;\r\n        }\r\n        this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\r\n    }\r\n}\r\nfunction dataURLBytes_(dataUrl) {\r\n    const parts = new DataURLParts(dataUrl);\r\n    if (parts.base64) {\r\n        return base64Bytes_(StringFormat.BASE64, parts.rest);\r\n    }\r\n    else {\r\n        return percentEncodedBytes_(parts.rest);\r\n    }\r\n}\r\nfunction dataURLContentType_(dataUrl) {\r\n    const parts = new DataURLParts(dataUrl);\r\n    return parts.contentType;\r\n}\r\nfunction endsWith(s, end) {\r\n    const longEnough = s.length >= end.length;\r\n    if (!longEnough) {\r\n        return false;\r\n    }\r\n    return s.substring(s.length - end.length) === end;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param opt_elideCopy - If true, doesn't copy mutable input data\r\n *     (e.g. Uint8Arrays). Pass true only if you know the objects will not be\r\n *     modified after this blob's construction.\r\n *\r\n * @internal\r\n */\r\nclass FbsBlob {\r\n    constructor(data, elideCopy) {\r\n        let size = 0;\r\n        let blobType = '';\r\n        if (isNativeBlob(data)) {\r\n            this.data_ = data;\r\n            size = data.size;\r\n            blobType = data.type;\r\n        }\r\n        else if (data instanceof ArrayBuffer) {\r\n            if (elideCopy) {\r\n                this.data_ = new Uint8Array(data);\r\n            }\r\n            else {\r\n                this.data_ = new Uint8Array(data.byteLength);\r\n                this.data_.set(new Uint8Array(data));\r\n            }\r\n            size = this.data_.length;\r\n        }\r\n        else if (data instanceof Uint8Array) {\r\n            if (elideCopy) {\r\n                this.data_ = data;\r\n            }\r\n            else {\r\n                this.data_ = new Uint8Array(data.length);\r\n                this.data_.set(data);\r\n            }\r\n            size = data.length;\r\n        }\r\n        this.size_ = size;\r\n        this.type_ = blobType;\r\n    }\r\n    size() {\r\n        return this.size_;\r\n    }\r\n    type() {\r\n        return this.type_;\r\n    }\r\n    slice(startByte, endByte) {\r\n        if (isNativeBlob(this.data_)) {\r\n            const realBlob = this.data_;\r\n            const sliced = sliceBlob(realBlob, startByte, endByte);\r\n            if (sliced === null) {\r\n                return null;\r\n            }\r\n            return new FbsBlob(sliced);\r\n        }\r\n        else {\r\n            const slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\r\n            return new FbsBlob(slice, true);\r\n        }\r\n    }\r\n    static getBlob(...args) {\r\n        if (isNativeBlobDefined()) {\r\n            const blobby = args.map((val) => {\r\n                if (val instanceof FbsBlob) {\r\n                    return val.data_;\r\n                }\r\n                else {\r\n                    return val;\r\n                }\r\n            });\r\n            return new FbsBlob(getBlob$1.apply(null, blobby));\r\n        }\r\n        else {\r\n            const uint8Arrays = args.map((val) => {\r\n                if (isString(val)) {\r\n                    return dataFromString(StringFormat.RAW, val).data;\r\n                }\r\n                else {\r\n                    // Blobs don't exist, so this has to be a Uint8Array.\r\n                    return val.data_;\r\n                }\r\n            });\r\n            let finalLength = 0;\r\n            uint8Arrays.forEach((array) => {\r\n                finalLength += array.byteLength;\r\n            });\r\n            const merged = new Uint8Array(finalLength);\r\n            let index = 0;\r\n            uint8Arrays.forEach((array) => {\r\n                for (let i = 0; i < array.length; i++) {\r\n                    merged[index++] = array[i];\r\n                }\r\n            });\r\n            return new FbsBlob(merged, true);\r\n        }\r\n    }\r\n    uploadData() {\r\n        return this.data_;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns the Object resulting from parsing the given JSON, or null if the\r\n * given string does not represent a JSON object.\r\n */\r\nfunction jsonObjectOrNull(s) {\r\n    let obj;\r\n    try {\r\n        obj = JSON.parse(s);\r\n    }\r\n    catch (e) {\r\n        return null;\r\n    }\r\n    if (isNonArrayObject(obj)) {\r\n        return obj;\r\n    }\r\n    else {\r\n        return null;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Contains helper methods for manipulating paths.\r\n */\r\n/**\r\n * @return Null if the path is already at the root.\r\n */\r\nfunction parent(path) {\r\n    if (path.length === 0) {\r\n        return null;\r\n    }\r\n    const index = path.lastIndexOf('/');\r\n    if (index === -1) {\r\n        return '';\r\n    }\r\n    const newPath = path.slice(0, index);\r\n    return newPath;\r\n}\r\nfunction child(path, childPath) {\r\n    const canonicalChildPath = childPath\r\n        .split('/')\r\n        .filter(component => component.length > 0)\r\n        .join('/');\r\n    if (path.length === 0) {\r\n        return canonicalChildPath;\r\n    }\r\n    else {\r\n        return path + '/' + canonicalChildPath;\r\n    }\r\n}\r\n/**\r\n * Returns the last component of a path.\r\n * '/foo/bar' -> 'bar'\r\n * '/foo/bar/baz/' -> 'baz/'\r\n * '/a' -> 'a'\r\n */\r\nfunction lastComponent(path) {\r\n    const index = path.lastIndexOf('/', path.length - 2);\r\n    if (index === -1) {\r\n        return path;\r\n    }\r\n    else {\r\n        return path.slice(index + 1);\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction noXform_(metadata, value) {\r\n    return value;\r\n}\r\nclass Mapping {\r\n    constructor(server, local, writable, xform) {\r\n        this.server = server;\r\n        this.local = local || server;\r\n        this.writable = !!writable;\r\n        this.xform = xform || noXform_;\r\n    }\r\n}\r\nlet mappings_ = null;\r\nfunction xformPath(fullPath) {\r\n    if (!isString(fullPath) || fullPath.length < 2) {\r\n        return fullPath;\r\n    }\r\n    else {\r\n        return lastComponent(fullPath);\r\n    }\r\n}\r\nfunction getMappings() {\r\n    if (mappings_) {\r\n        return mappings_;\r\n    }\r\n    const mappings = [];\r\n    mappings.push(new Mapping('bucket'));\r\n    mappings.push(new Mapping('generation'));\r\n    mappings.push(new Mapping('metageneration'));\r\n    mappings.push(new Mapping('name', 'fullPath', true));\r\n    function mappingsXformPath(_metadata, fullPath) {\r\n        return xformPath(fullPath);\r\n    }\r\n    const nameMapping = new Mapping('name');\r\n    nameMapping.xform = mappingsXformPath;\r\n    mappings.push(nameMapping);\r\n    /**\r\n     * Coerces the second param to a number, if it is defined.\r\n     */\r\n    function xformSize(_metadata, size) {\r\n        if (size !== undefined) {\r\n            return Number(size);\r\n        }\r\n        else {\r\n            return size;\r\n        }\r\n    }\r\n    const sizeMapping = new Mapping('size');\r\n    sizeMapping.xform = xformSize;\r\n    mappings.push(sizeMapping);\r\n    mappings.push(new Mapping('timeCreated'));\r\n    mappings.push(new Mapping('updated'));\r\n    mappings.push(new Mapping('md5Hash', null, true));\r\n    mappings.push(new Mapping('cacheControl', null, true));\r\n    mappings.push(new Mapping('contentDisposition', null, true));\r\n    mappings.push(new Mapping('contentEncoding', null, true));\r\n    mappings.push(new Mapping('contentLanguage', null, true));\r\n    mappings.push(new Mapping('contentType', null, true));\r\n    mappings.push(new Mapping('metadata', 'customMetadata', true));\r\n    mappings_ = mappings;\r\n    return mappings_;\r\n}\r\nfunction addRef(metadata, service) {\r\n    function generateRef() {\r\n        const bucket = metadata['bucket'];\r\n        const path = metadata['fullPath'];\r\n        const loc = new Location(bucket, path);\r\n        return service._makeStorageReference(loc);\r\n    }\r\n    Object.defineProperty(metadata, 'ref', { get: generateRef });\r\n}\r\nfunction fromResource(service, resource, mappings) {\r\n    const metadata = {};\r\n    metadata['type'] = 'file';\r\n    const len = mappings.length;\r\n    for (let i = 0; i < len; i++) {\r\n        const mapping = mappings[i];\r\n        metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\r\n    }\r\n    addRef(metadata, service);\r\n    return metadata;\r\n}\r\nfunction fromResourceString(service, resourceString, mappings) {\r\n    const obj = jsonObjectOrNull(resourceString);\r\n    if (obj === null) {\r\n        return null;\r\n    }\r\n    const resource = obj;\r\n    return fromResource(service, resource, mappings);\r\n}\r\nfunction downloadUrlFromResourceString(metadata, resourceString, host, protocol) {\r\n    const obj = jsonObjectOrNull(resourceString);\r\n    if (obj === null) {\r\n        return null;\r\n    }\r\n    if (!isString(obj['downloadTokens'])) {\r\n        // This can happen if objects are uploaded through GCS and retrieved\r\n        // through list, so we don't want to throw an Error.\r\n        return null;\r\n    }\r\n    const tokens = obj['downloadTokens'];\r\n    if (tokens.length === 0) {\r\n        return null;\r\n    }\r\n    const encode = encodeURIComponent;\r\n    const tokensList = tokens.split(',');\r\n    const urls = tokensList.map((token) => {\r\n        const bucket = metadata['bucket'];\r\n        const path = metadata['fullPath'];\r\n        const urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\r\n        const base = makeUrl(urlPart, host, protocol);\r\n        const queryString = makeQueryString({\r\n            alt: 'media',\r\n            token\r\n        });\r\n        return base + queryString;\r\n    });\r\n    return urls[0];\r\n}\r\nfunction toResourceString(metadata, mappings) {\r\n    const resource = {};\r\n    const len = mappings.length;\r\n    for (let i = 0; i < len; i++) {\r\n        const mapping = mappings[i];\r\n        if (mapping.writable) {\r\n            resource[mapping.server] = metadata[mapping.local];\r\n        }\r\n    }\r\n    return JSON.stringify(resource);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PREFIXES_KEY = 'prefixes';\r\nconst ITEMS_KEY = 'items';\r\nfunction fromBackendResponse(service, bucket, resource) {\r\n    const listResult = {\r\n        prefixes: [],\r\n        items: [],\r\n        nextPageToken: resource['nextPageToken']\r\n    };\r\n    if (resource[PREFIXES_KEY]) {\r\n        for (const path of resource[PREFIXES_KEY]) {\r\n            const pathWithoutTrailingSlash = path.replace(/\\/$/, '');\r\n            const reference = service._makeStorageReference(new Location(bucket, pathWithoutTrailingSlash));\r\n            listResult.prefixes.push(reference);\r\n        }\r\n    }\r\n    if (resource[ITEMS_KEY]) {\r\n        for (const item of resource[ITEMS_KEY]) {\r\n            const reference = service._makeStorageReference(new Location(bucket, item['name']));\r\n            listResult.items.push(reference);\r\n        }\r\n    }\r\n    return listResult;\r\n}\r\nfunction fromResponseString(service, bucket, resourceString) {\r\n    const obj = jsonObjectOrNull(resourceString);\r\n    if (obj === null) {\r\n        return null;\r\n    }\r\n    const resource = obj;\r\n    return fromBackendResponse(service, bucket, resource);\r\n}\n\n/**\r\n * Contains a fully specified request.\r\n *\r\n * @param I - the type of the backend's network response.\r\n * @param O - the output response type used by the rest of the SDK.\r\n */\r\nclass RequestInfo {\r\n    constructor(url, method, \r\n    /**\r\n     * Returns the value with which to resolve the request's promise. Only called\r\n     * if the request is successful. Throw from this function to reject the\r\n     * returned Request's promise with the thrown error.\r\n     * Note: The XhrIo passed to this function may be reused after this callback\r\n     * returns. Do not keep a reference to it in any way.\r\n     */\r\n    handler, timeout) {\r\n        this.url = url;\r\n        this.method = method;\r\n        this.handler = handler;\r\n        this.timeout = timeout;\r\n        this.urlParams = {};\r\n        this.headers = {};\r\n        this.body = null;\r\n        this.errorHandler = null;\r\n        /**\r\n         * Called with the current number of bytes uploaded and total size (-1 if not\r\n         * computable) of the request body (i.e. used to report upload progress).\r\n         */\r\n        this.progressCallback = null;\r\n        this.successCodes = [200];\r\n        this.additionalRetryCodes = [];\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws the UNKNOWN StorageError if cndn is false.\r\n */\r\nfunction handlerCheck(cndn) {\r\n    if (!cndn) {\r\n        throw unknown();\r\n    }\r\n}\r\nfunction metadataHandler(service, mappings) {\r\n    function handler(xhr, text) {\r\n        const metadata = fromResourceString(service, text, mappings);\r\n        handlerCheck(metadata !== null);\r\n        return metadata;\r\n    }\r\n    return handler;\r\n}\r\nfunction listHandler(service, bucket) {\r\n    function handler(xhr, text) {\r\n        const listResult = fromResponseString(service, bucket, text);\r\n        handlerCheck(listResult !== null);\r\n        return listResult;\r\n    }\r\n    return handler;\r\n}\r\nfunction downloadUrlHandler(service, mappings) {\r\n    function handler(xhr, text) {\r\n        const metadata = fromResourceString(service, text, mappings);\r\n        handlerCheck(metadata !== null);\r\n        return downloadUrlFromResourceString(metadata, text, service.host, service._protocol);\r\n    }\r\n    return handler;\r\n}\r\nfunction sharedErrorHandler(location) {\r\n    function errorHandler(xhr, err) {\r\n        let newErr;\r\n        if (xhr.getStatus() === 401) {\r\n            if (\r\n            // This exact message string is the only consistent part of the\r\n            // server's error response that identifies it as an App Check error.\r\n            xhr.getErrorText().includes('Firebase App Check token is invalid')) {\r\n                newErr = unauthorizedApp();\r\n            }\r\n            else {\r\n                newErr = unauthenticated();\r\n            }\r\n        }\r\n        else {\r\n            if (xhr.getStatus() === 402) {\r\n                newErr = quotaExceeded(location.bucket);\r\n            }\r\n            else {\r\n                if (xhr.getStatus() === 403) {\r\n                    newErr = unauthorized(location.path);\r\n                }\r\n                else {\r\n                    newErr = err;\r\n                }\r\n            }\r\n        }\r\n        newErr.status = xhr.getStatus();\r\n        newErr.serverResponse = err.serverResponse;\r\n        return newErr;\r\n    }\r\n    return errorHandler;\r\n}\r\nfunction objectErrorHandler(location) {\r\n    const shared = sharedErrorHandler(location);\r\n    function errorHandler(xhr, err) {\r\n        let newErr = shared(xhr, err);\r\n        if (xhr.getStatus() === 404) {\r\n            newErr = objectNotFound(location.path);\r\n        }\r\n        newErr.serverResponse = err.serverResponse;\r\n        return newErr;\r\n    }\r\n    return errorHandler;\r\n}\r\nfunction getMetadata$2(service, location, mappings) {\r\n    const urlPart = location.fullServerUrl();\r\n    const url = makeUrl(urlPart, service.host, service._protocol);\r\n    const method = 'GET';\r\n    const timeout = service.maxOperationRetryTime;\r\n    const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);\r\n    requestInfo.errorHandler = objectErrorHandler(location);\r\n    return requestInfo;\r\n}\r\nfunction list$2(service, location, delimiter, pageToken, maxResults) {\r\n    const urlParams = {};\r\n    if (location.isRoot) {\r\n        urlParams['prefix'] = '';\r\n    }\r\n    else {\r\n        urlParams['prefix'] = location.path + '/';\r\n    }\r\n    if (delimiter && delimiter.length > 0) {\r\n        urlParams['delimiter'] = delimiter;\r\n    }\r\n    if (pageToken) {\r\n        urlParams['pageToken'] = pageToken;\r\n    }\r\n    if (maxResults) {\r\n        urlParams['maxResults'] = maxResults;\r\n    }\r\n    const urlPart = location.bucketOnlyServerUrl();\r\n    const url = makeUrl(urlPart, service.host, service._protocol);\r\n    const method = 'GET';\r\n    const timeout = service.maxOperationRetryTime;\r\n    const requestInfo = new RequestInfo(url, method, listHandler(service, location.bucket), timeout);\r\n    requestInfo.urlParams = urlParams;\r\n    requestInfo.errorHandler = sharedErrorHandler(location);\r\n    return requestInfo;\r\n}\r\nfunction getBytes$1(service, location, maxDownloadSizeBytes) {\r\n    const urlPart = location.fullServerUrl();\r\n    const url = makeUrl(urlPart, service.host, service._protocol) + '?alt=media';\r\n    const method = 'GET';\r\n    const timeout = service.maxOperationRetryTime;\r\n    const requestInfo = new RequestInfo(url, method, (_, data) => data, timeout);\r\n    requestInfo.errorHandler = objectErrorHandler(location);\r\n    if (maxDownloadSizeBytes !== undefined) {\r\n        requestInfo.headers['Range'] = `bytes=0-${maxDownloadSizeBytes}`;\r\n        requestInfo.successCodes = [200 /* OK */, 206 /* Partial Content */];\r\n    }\r\n    return requestInfo;\r\n}\r\nfunction getDownloadUrl(service, location, mappings) {\r\n    const urlPart = location.fullServerUrl();\r\n    const url = makeUrl(urlPart, service.host, service._protocol);\r\n    const method = 'GET';\r\n    const timeout = service.maxOperationRetryTime;\r\n    const requestInfo = new RequestInfo(url, method, downloadUrlHandler(service, mappings), timeout);\r\n    requestInfo.errorHandler = objectErrorHandler(location);\r\n    return requestInfo;\r\n}\r\nfunction updateMetadata$2(service, location, metadata, mappings) {\r\n    const urlPart = location.fullServerUrl();\r\n    const url = makeUrl(urlPart, service.host, service._protocol);\r\n    const method = 'PATCH';\r\n    const body = toResourceString(metadata, mappings);\r\n    const headers = { 'Content-Type': 'application/json; charset=utf-8' };\r\n    const timeout = service.maxOperationRetryTime;\r\n    const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);\r\n    requestInfo.headers = headers;\r\n    requestInfo.body = body;\r\n    requestInfo.errorHandler = objectErrorHandler(location);\r\n    return requestInfo;\r\n}\r\nfunction deleteObject$2(service, location) {\r\n    const urlPart = location.fullServerUrl();\r\n    const url = makeUrl(urlPart, service.host, service._protocol);\r\n    const method = 'DELETE';\r\n    const timeout = service.maxOperationRetryTime;\r\n    function handler(_xhr, _text) { }\r\n    const requestInfo = new RequestInfo(url, method, handler, timeout);\r\n    requestInfo.successCodes = [200, 204];\r\n    requestInfo.errorHandler = objectErrorHandler(location);\r\n    return requestInfo;\r\n}\r\nfunction determineContentType_(metadata, blob) {\r\n    return ((metadata && metadata['contentType']) ||\r\n        (blob && blob.type()) ||\r\n        'application/octet-stream');\r\n}\r\nfunction metadataForUpload_(location, blob, metadata) {\r\n    const metadataClone = Object.assign({}, metadata);\r\n    metadataClone['fullPath'] = location.path;\r\n    metadataClone['size'] = blob.size();\r\n    if (!metadataClone['contentType']) {\r\n        metadataClone['contentType'] = determineContentType_(null, blob);\r\n    }\r\n    return metadataClone;\r\n}\r\n/**\r\n * Prepare RequestInfo for uploads as Content-Type: multipart.\r\n */\r\nfunction multipartUpload(service, location, mappings, blob, metadata) {\r\n    const urlPart = location.bucketOnlyServerUrl();\r\n    const headers = {\r\n        'X-Goog-Upload-Protocol': 'multipart'\r\n    };\r\n    function genBoundary() {\r\n        let str = '';\r\n        for (let i = 0; i < 2; i++) {\r\n            str = str + Math.random().toString().slice(2);\r\n        }\r\n        return str;\r\n    }\r\n    const boundary = genBoundary();\r\n    headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\r\n    const metadata_ = metadataForUpload_(location, blob, metadata);\r\n    const metadataString = toResourceString(metadata_, mappings);\r\n    const preBlobPart = '--' +\r\n        boundary +\r\n        '\\r\\n' +\r\n        'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\r\n        metadataString +\r\n        '\\r\\n--' +\r\n        boundary +\r\n        '\\r\\n' +\r\n        'Content-Type: ' +\r\n        metadata_['contentType'] +\r\n        '\\r\\n\\r\\n';\r\n    const postBlobPart = '\\r\\n--' + boundary + '--';\r\n    const body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\r\n    if (body === null) {\r\n        throw cannotSliceBlob();\r\n    }\r\n    const urlParams = { name: metadata_['fullPath'] };\r\n    const url = makeUrl(urlPart, service.host, service._protocol);\r\n    const method = 'POST';\r\n    const timeout = service.maxUploadRetryTime;\r\n    const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);\r\n    requestInfo.urlParams = urlParams;\r\n    requestInfo.headers = headers;\r\n    requestInfo.body = body.uploadData();\r\n    requestInfo.errorHandler = sharedErrorHandler(location);\r\n    return requestInfo;\r\n}\r\n/**\r\n * @param current The number of bytes that have been uploaded so far.\r\n * @param total The total number of bytes in the upload.\r\n * @param opt_finalized True if the server has finished the upload.\r\n * @param opt_metadata The upload metadata, should\r\n *     only be passed if opt_finalized is true.\r\n */\r\nclass ResumableUploadStatus {\r\n    constructor(current, total, finalized, metadata) {\r\n        this.current = current;\r\n        this.total = total;\r\n        this.finalized = !!finalized;\r\n        this.metadata = metadata || null;\r\n    }\r\n}\r\nfunction checkResumeHeader_(xhr, allowed) {\r\n    let status = null;\r\n    try {\r\n        status = xhr.getResponseHeader('X-Goog-Upload-Status');\r\n    }\r\n    catch (e) {\r\n        handlerCheck(false);\r\n    }\r\n    const allowedStatus = allowed || ['active'];\r\n    handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);\r\n    return status;\r\n}\r\nfunction createResumableUpload(service, location, mappings, blob, metadata) {\r\n    const urlPart = location.bucketOnlyServerUrl();\r\n    const metadataForUpload = metadataForUpload_(location, blob, metadata);\r\n    const urlParams = { name: metadataForUpload['fullPath'] };\r\n    const url = makeUrl(urlPart, service.host, service._protocol);\r\n    const method = 'POST';\r\n    const headers = {\r\n        'X-Goog-Upload-Protocol': 'resumable',\r\n        'X-Goog-Upload-Command': 'start',\r\n        'X-Goog-Upload-Header-Content-Length': `${blob.size()}`,\r\n        'X-Goog-Upload-Header-Content-Type': metadataForUpload['contentType'],\r\n        'Content-Type': 'application/json; charset=utf-8'\r\n    };\r\n    const body = toResourceString(metadataForUpload, mappings);\r\n    const timeout = service.maxUploadRetryTime;\r\n    function handler(xhr) {\r\n        checkResumeHeader_(xhr);\r\n        let url;\r\n        try {\r\n            url = xhr.getResponseHeader('X-Goog-Upload-URL');\r\n        }\r\n        catch (e) {\r\n            handlerCheck(false);\r\n        }\r\n        handlerCheck(isString(url));\r\n        return url;\r\n    }\r\n    const requestInfo = new RequestInfo(url, method, handler, timeout);\r\n    requestInfo.urlParams = urlParams;\r\n    requestInfo.headers = headers;\r\n    requestInfo.body = body;\r\n    requestInfo.errorHandler = sharedErrorHandler(location);\r\n    return requestInfo;\r\n}\r\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n */\r\nfunction getResumableUploadStatus(service, location, url, blob) {\r\n    const headers = { 'X-Goog-Upload-Command': 'query' };\r\n    function handler(xhr) {\r\n        const status = checkResumeHeader_(xhr, ['active', 'final']);\r\n        let sizeString = null;\r\n        try {\r\n            sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\r\n        }\r\n        catch (e) {\r\n            handlerCheck(false);\r\n        }\r\n        if (!sizeString) {\r\n            // null or empty string\r\n            handlerCheck(false);\r\n        }\r\n        const size = Number(sizeString);\r\n        handlerCheck(!isNaN(size));\r\n        return new ResumableUploadStatus(size, blob.size(), status === 'final');\r\n    }\r\n    const method = 'POST';\r\n    const timeout = service.maxUploadRetryTime;\r\n    const requestInfo = new RequestInfo(url, method, handler, timeout);\r\n    requestInfo.headers = headers;\r\n    requestInfo.errorHandler = sharedErrorHandler(location);\r\n    return requestInfo;\r\n}\r\n/**\r\n * Any uploads via the resumable upload API must transfer a number of bytes\r\n * that is a multiple of this number.\r\n */\r\nconst RESUMABLE_UPLOAD_CHUNK_SIZE = 256 * 1024;\r\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n * @param chunkSize Number of bytes to upload.\r\n * @param status The previous status.\r\n *     If not passed or null, we start from the beginning.\r\n * @throws fbs.Error If the upload is already complete, the passed in status\r\n *     has a final size inconsistent with the blob, or the blob cannot be sliced\r\n *     for upload.\r\n */\r\nfunction continueResumableUpload(location, service, url, blob, chunkSize, mappings, status, progressCallback) {\r\n    // TODO(andysoto): standardize on internal asserts\r\n    // assert(!(opt_status && opt_status.finalized));\r\n    const status_ = new ResumableUploadStatus(0, 0);\r\n    if (status) {\r\n        status_.current = status.current;\r\n        status_.total = status.total;\r\n    }\r\n    else {\r\n        status_.current = 0;\r\n        status_.total = blob.size();\r\n    }\r\n    if (blob.size() !== status_.total) {\r\n        throw serverFileWrongSize();\r\n    }\r\n    const bytesLeft = status_.total - status_.current;\r\n    let bytesToUpload = bytesLeft;\r\n    if (chunkSize > 0) {\r\n        bytesToUpload = Math.min(bytesToUpload, chunkSize);\r\n    }\r\n    const startByte = status_.current;\r\n    const endByte = startByte + bytesToUpload;\r\n    let uploadCommand = '';\r\n    if (bytesToUpload === 0) {\r\n        uploadCommand = 'finalize';\r\n    }\r\n    else if (bytesLeft === bytesToUpload) {\r\n        uploadCommand = 'upload, finalize';\r\n    }\r\n    else {\r\n        uploadCommand = 'upload';\r\n    }\r\n    const headers = {\r\n        'X-Goog-Upload-Command': uploadCommand,\r\n        'X-Goog-Upload-Offset': `${status_.current}`\r\n    };\r\n    const body = blob.slice(startByte, endByte);\r\n    if (body === null) {\r\n        throw cannotSliceBlob();\r\n    }\r\n    function handler(xhr, text) {\r\n        // TODO(andysoto): Verify the MD5 of each uploaded range:\r\n        // the 'x-range-md5' header comes back with status code 308 responses.\r\n        // We'll only be able to bail out though, because you can't re-upload a\r\n        // range that you previously uploaded.\r\n        const uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\r\n        const newCurrent = status_.current + bytesToUpload;\r\n        const size = blob.size();\r\n        let metadata;\r\n        if (uploadStatus === 'final') {\r\n            metadata = metadataHandler(service, mappings)(xhr, text);\r\n        }\r\n        else {\r\n            metadata = null;\r\n        }\r\n        return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\r\n    }\r\n    const method = 'POST';\r\n    const timeout = service.maxUploadRetryTime;\r\n    const requestInfo = new RequestInfo(url, method, handler, timeout);\r\n    requestInfo.headers = headers;\r\n    requestInfo.body = body.uploadData();\r\n    requestInfo.progressCallback = progressCallback || null;\r\n    requestInfo.errorHandler = sharedErrorHandler(location);\r\n    return requestInfo;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An event that is triggered on a task.\r\n * @internal\r\n */\r\nconst TaskEvent = {\r\n    /**\r\n     * For this event,\r\n     * <ul>\r\n     *   <li>The `next` function is triggered on progress updates and when the\r\n     *       task is paused/resumed with an `UploadTaskSnapshot` as the first\r\n     *       argument.</li>\r\n     *   <li>The `error` function is triggered if the upload is canceled or fails\r\n     *       for another reason.</li>\r\n     *   <li>The `complete` function is triggered if the upload completes\r\n     *       successfully.</li>\r\n     * </ul>\r\n     */\r\n    STATE_CHANGED: 'state_changed'\r\n};\r\n// type keys = keyof TaskState\r\n/**\r\n * Represents the current state of a running upload.\r\n * @internal\r\n */\r\nconst TaskState = {\r\n    /** The task is currently transferring data. */\r\n    RUNNING: 'running',\r\n    /** The task was paused by the user. */\r\n    PAUSED: 'paused',\r\n    /** The task completed successfully. */\r\n    SUCCESS: 'success',\r\n    /** The task was canceled. */\r\n    CANCELED: 'canceled',\r\n    /** The task failed with an error. */\r\n    ERROR: 'error'\r\n};\r\nfunction taskStateFromInternalTaskState(state) {\r\n    switch (state) {\r\n        case \"running\" /* InternalTaskState.RUNNING */:\r\n        case \"pausing\" /* InternalTaskState.PAUSING */:\r\n        case \"canceling\" /* InternalTaskState.CANCELING */:\r\n            return TaskState.RUNNING;\r\n        case \"paused\" /* InternalTaskState.PAUSED */:\r\n            return TaskState.PAUSED;\r\n        case \"success\" /* InternalTaskState.SUCCESS */:\r\n            return TaskState.SUCCESS;\r\n        case \"canceled\" /* InternalTaskState.CANCELED */:\r\n            return TaskState.CANCELED;\r\n        case \"error\" /* InternalTaskState.ERROR */:\r\n            return TaskState.ERROR;\r\n        default:\r\n            // TODO(andysoto): assert(false);\r\n            return TaskState.ERROR;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Observer {\r\n    constructor(nextOrObserver, error, complete) {\r\n        const asFunctions = isFunction(nextOrObserver) || error != null || complete != null;\r\n        if (asFunctions) {\r\n            this.next = nextOrObserver;\r\n            this.error = error !== null && error !== void 0 ? error : undefined;\r\n            this.complete = complete !== null && complete !== void 0 ? complete : undefined;\r\n        }\r\n        else {\r\n            const observer = nextOrObserver;\r\n            this.next = observer.next;\r\n            this.error = observer.error;\r\n            this.complete = observer.complete;\r\n        }\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a function that invokes f with its arguments asynchronously as a\r\n * microtask, i.e. as soon as possible after the current script returns back\r\n * into browser code.\r\n */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(f) {\r\n    return (...argsToForward) => {\r\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n        Promise.resolve().then(() => f(...argsToForward));\r\n    };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** An override for the text-based Connection. Used in tests. */\r\nlet textFactoryOverride = null;\r\n/**\r\n * Network layer for browsers. We use this instead of goog.net.XhrIo because\r\n * goog.net.XhrIo is hyuuuuge and doesn't work in React Native on Android.\r\n */\r\nclass XhrConnection {\r\n    constructor() {\r\n        this.sent_ = false;\r\n        this.xhr_ = new XMLHttpRequest();\r\n        this.initXhr();\r\n        this.errorCode_ = ErrorCode.NO_ERROR;\r\n        this.sendPromise_ = new Promise(resolve => {\r\n            this.xhr_.addEventListener('abort', () => {\r\n                this.errorCode_ = ErrorCode.ABORT;\r\n                resolve();\r\n            });\r\n            this.xhr_.addEventListener('error', () => {\r\n                this.errorCode_ = ErrorCode.NETWORK_ERROR;\r\n                resolve();\r\n            });\r\n            this.xhr_.addEventListener('load', () => {\r\n                resolve();\r\n            });\r\n        });\r\n    }\r\n    send(url, method, body, headers) {\r\n        if (this.sent_) {\r\n            throw internalError('cannot .send() more than once');\r\n        }\r\n        this.sent_ = true;\r\n        this.xhr_.open(method, url, true);\r\n        if (headers !== undefined) {\r\n            for (const key in headers) {\r\n                if (headers.hasOwnProperty(key)) {\r\n                    this.xhr_.setRequestHeader(key, headers[key].toString());\r\n                }\r\n            }\r\n        }\r\n        if (body !== undefined) {\r\n            this.xhr_.send(body);\r\n        }\r\n        else {\r\n            this.xhr_.send();\r\n        }\r\n        return this.sendPromise_;\r\n    }\r\n    getErrorCode() {\r\n        if (!this.sent_) {\r\n            throw internalError('cannot .getErrorCode() before sending');\r\n        }\r\n        return this.errorCode_;\r\n    }\r\n    getStatus() {\r\n        if (!this.sent_) {\r\n            throw internalError('cannot .getStatus() before sending');\r\n        }\r\n        try {\r\n            return this.xhr_.status;\r\n        }\r\n        catch (e) {\r\n            return -1;\r\n        }\r\n    }\r\n    getResponse() {\r\n        if (!this.sent_) {\r\n            throw internalError('cannot .getResponse() before sending');\r\n        }\r\n        return this.xhr_.response;\r\n    }\r\n    getErrorText() {\r\n        if (!this.sent_) {\r\n            throw internalError('cannot .getErrorText() before sending');\r\n        }\r\n        return this.xhr_.statusText;\r\n    }\r\n    /** Aborts the request. */\r\n    abort() {\r\n        this.xhr_.abort();\r\n    }\r\n    getResponseHeader(header) {\r\n        return this.xhr_.getResponseHeader(header);\r\n    }\r\n    addUploadProgressListener(listener) {\r\n        if (this.xhr_.upload != null) {\r\n            this.xhr_.upload.addEventListener('progress', listener);\r\n        }\r\n    }\r\n    removeUploadProgressListener(listener) {\r\n        if (this.xhr_.upload != null) {\r\n            this.xhr_.upload.removeEventListener('progress', listener);\r\n        }\r\n    }\r\n}\r\nclass XhrTextConnection extends XhrConnection {\r\n    initXhr() {\r\n        this.xhr_.responseType = 'text';\r\n    }\r\n}\r\nfunction newTextConnection() {\r\n    return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();\r\n}\r\nclass XhrBytesConnection extends XhrConnection {\r\n    initXhr() {\r\n        this.xhr_.responseType = 'arraybuffer';\r\n    }\r\n}\r\nfunction newBytesConnection() {\r\n    return new XhrBytesConnection();\r\n}\r\nclass XhrBlobConnection extends XhrConnection {\r\n    initXhr() {\r\n        this.xhr_.responseType = 'blob';\r\n    }\r\n}\r\nfunction newBlobConnection() {\r\n    return new XhrBlobConnection();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\r\n * upload and manage callbacks for various events.\r\n * @internal\r\n */\r\nclass UploadTask {\r\n    /**\r\n     * @param ref - The firebaseStorage.Reference object this task came\r\n     *     from, untyped to avoid cyclic dependencies.\r\n     * @param blob - The blob to upload.\r\n     */\r\n    constructor(ref, blob, metadata = null) {\r\n        /**\r\n         * Number of bytes transferred so far.\r\n         */\r\n        this._transferred = 0;\r\n        this._needToFetchStatus = false;\r\n        this._needToFetchMetadata = false;\r\n        this._observers = [];\r\n        this._error = undefined;\r\n        this._uploadUrl = undefined;\r\n        this._request = undefined;\r\n        this._chunkMultiplier = 1;\r\n        this._resolve = undefined;\r\n        this._reject = undefined;\r\n        this._ref = ref;\r\n        this._blob = blob;\r\n        this._metadata = metadata;\r\n        this._mappings = getMappings();\r\n        this._resumable = this._shouldDoResumable(this._blob);\r\n        this._state = \"running\" /* InternalTaskState.RUNNING */;\r\n        this._errorHandler = error => {\r\n            this._request = undefined;\r\n            this._chunkMultiplier = 1;\r\n            if (error._codeEquals(StorageErrorCode.CANCELED)) {\r\n                this._needToFetchStatus = true;\r\n                this.completeTransitions_();\r\n            }\r\n            else {\r\n                const backoffExpired = this.isExponentialBackoffExpired();\r\n                if (isRetryStatusCode(error.status, [])) {\r\n                    if (backoffExpired) {\r\n                        error = retryLimitExceeded();\r\n                    }\r\n                    else {\r\n                        this.sleepTime = Math.max(this.sleepTime * 2, DEFAULT_MIN_SLEEP_TIME_MILLIS);\r\n                        this._needToFetchStatus = true;\r\n                        this.completeTransitions_();\r\n                        return;\r\n                    }\r\n                }\r\n                this._error = error;\r\n                this._transition(\"error\" /* InternalTaskState.ERROR */);\r\n            }\r\n        };\r\n        this._metadataErrorHandler = error => {\r\n            this._request = undefined;\r\n            if (error._codeEquals(StorageErrorCode.CANCELED)) {\r\n                this.completeTransitions_();\r\n            }\r\n            else {\r\n                this._error = error;\r\n                this._transition(\"error\" /* InternalTaskState.ERROR */);\r\n            }\r\n        };\r\n        this.sleepTime = 0;\r\n        this.maxSleepTime = this._ref.storage.maxUploadRetryTime;\r\n        this._promise = new Promise((resolve, reject) => {\r\n            this._resolve = resolve;\r\n            this._reject = reject;\r\n            this._start();\r\n        });\r\n        // Prevent uncaught rejections on the internal promise from bubbling out\r\n        // to the top level with a dummy handler.\r\n        this._promise.then(null, () => { });\r\n    }\r\n    isExponentialBackoffExpired() {\r\n        return this.sleepTime > this.maxSleepTime;\r\n    }\r\n    _makeProgressCallback() {\r\n        const sizeBefore = this._transferred;\r\n        return loaded => this._updateProgress(sizeBefore + loaded);\r\n    }\r\n    _shouldDoResumable(blob) {\r\n        return blob.size() > 256 * 1024;\r\n    }\r\n    _start() {\r\n        if (this._state !== \"running\" /* InternalTaskState.RUNNING */) {\r\n            // This can happen if someone pauses us in a resume callback, for example.\r\n            return;\r\n        }\r\n        if (this._request !== undefined) {\r\n            return;\r\n        }\r\n        if (this._resumable) {\r\n            if (this._uploadUrl === undefined) {\r\n                this._createResumable();\r\n            }\r\n            else {\r\n                if (this._needToFetchStatus) {\r\n                    this._fetchStatus();\r\n                }\r\n                else {\r\n                    if (this._needToFetchMetadata) {\r\n                        // Happens if we miss the metadata on upload completion.\r\n                        this._fetchMetadata();\r\n                    }\r\n                    else {\r\n                        this.pendingTimeout = setTimeout(() => {\r\n                            this.pendingTimeout = undefined;\r\n                            this._continueUpload();\r\n                        }, this.sleepTime);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            this._oneShotUpload();\r\n        }\r\n    }\r\n    _resolveToken(callback) {\r\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n        Promise.all([\r\n            this._ref.storage._getAuthToken(),\r\n            this._ref.storage._getAppCheckToken()\r\n        ]).then(([authToken, appCheckToken]) => {\r\n            switch (this._state) {\r\n                case \"running\" /* InternalTaskState.RUNNING */:\r\n                    callback(authToken, appCheckToken);\r\n                    break;\r\n                case \"canceling\" /* InternalTaskState.CANCELING */:\r\n                    this._transition(\"canceled\" /* InternalTaskState.CANCELED */);\r\n                    break;\r\n                case \"pausing\" /* InternalTaskState.PAUSING */:\r\n                    this._transition(\"paused\" /* InternalTaskState.PAUSED */);\r\n                    break;\r\n            }\r\n        });\r\n    }\r\n    // TODO(andysoto): assert false\r\n    _createResumable() {\r\n        this._resolveToken((authToken, appCheckToken) => {\r\n            const requestInfo = createResumableUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);\r\n            const createRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);\r\n            this._request = createRequest;\r\n            createRequest.getPromise().then((url) => {\r\n                this._request = undefined;\r\n                this._uploadUrl = url;\r\n                this._needToFetchStatus = false;\r\n                this.completeTransitions_();\r\n            }, this._errorHandler);\r\n        });\r\n    }\r\n    _fetchStatus() {\r\n        // TODO(andysoto): assert(this.uploadUrl_ !== null);\r\n        const url = this._uploadUrl;\r\n        this._resolveToken((authToken, appCheckToken) => {\r\n            const requestInfo = getResumableUploadStatus(this._ref.storage, this._ref._location, url, this._blob);\r\n            const statusRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);\r\n            this._request = statusRequest;\r\n            statusRequest.getPromise().then(status => {\r\n                status = status;\r\n                this._request = undefined;\r\n                this._updateProgress(status.current);\r\n                this._needToFetchStatus = false;\r\n                if (status.finalized) {\r\n                    this._needToFetchMetadata = true;\r\n                }\r\n                this.completeTransitions_();\r\n            }, this._errorHandler);\r\n        });\r\n    }\r\n    _continueUpload() {\r\n        const chunkSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\r\n        const status = new ResumableUploadStatus(this._transferred, this._blob.size());\r\n        // TODO(andysoto): assert(this.uploadUrl_ !== null);\r\n        const url = this._uploadUrl;\r\n        this._resolveToken((authToken, appCheckToken) => {\r\n            let requestInfo;\r\n            try {\r\n                requestInfo = continueResumableUpload(this._ref._location, this._ref.storage, url, this._blob, chunkSize, this._mappings, status, this._makeProgressCallback());\r\n            }\r\n            catch (e) {\r\n                this._error = e;\r\n                this._transition(\"error\" /* InternalTaskState.ERROR */);\r\n                return;\r\n            }\r\n            const uploadRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken, \r\n            /*retry=*/ false // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.\r\n            );\r\n            this._request = uploadRequest;\r\n            uploadRequest.getPromise().then((newStatus) => {\r\n                this._increaseMultiplier();\r\n                this._request = undefined;\r\n                this._updateProgress(newStatus.current);\r\n                if (newStatus.finalized) {\r\n                    this._metadata = newStatus.metadata;\r\n                    this._transition(\"success\" /* InternalTaskState.SUCCESS */);\r\n                }\r\n                else {\r\n                    this.completeTransitions_();\r\n                }\r\n            }, this._errorHandler);\r\n        });\r\n    }\r\n    _increaseMultiplier() {\r\n        const currentSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\r\n        // Max chunk size is 32M.\r\n        if (currentSize * 2 < 32 * 1024 * 1024) {\r\n            this._chunkMultiplier *= 2;\r\n        }\r\n    }\r\n    _fetchMetadata() {\r\n        this._resolveToken((authToken, appCheckToken) => {\r\n            const requestInfo = getMetadata$2(this._ref.storage, this._ref._location, this._mappings);\r\n            const metadataRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);\r\n            this._request = metadataRequest;\r\n            metadataRequest.getPromise().then(metadata => {\r\n                this._request = undefined;\r\n                this._metadata = metadata;\r\n                this._transition(\"success\" /* InternalTaskState.SUCCESS */);\r\n            }, this._metadataErrorHandler);\r\n        });\r\n    }\r\n    _oneShotUpload() {\r\n        this._resolveToken((authToken, appCheckToken) => {\r\n            const requestInfo = multipartUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);\r\n            const multipartRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);\r\n            this._request = multipartRequest;\r\n            multipartRequest.getPromise().then(metadata => {\r\n                this._request = undefined;\r\n                this._metadata = metadata;\r\n                this._updateProgress(this._blob.size());\r\n                this._transition(\"success\" /* InternalTaskState.SUCCESS */);\r\n            }, this._errorHandler);\r\n        });\r\n    }\r\n    _updateProgress(transferred) {\r\n        const old = this._transferred;\r\n        this._transferred = transferred;\r\n        // A progress update can make the \"transferred\" value smaller (e.g. a\r\n        // partial upload not completed by server, after which the \"transferred\"\r\n        // value may reset to the value at the beginning of the request).\r\n        if (this._transferred !== old) {\r\n            this._notifyObservers();\r\n        }\r\n    }\r\n    _transition(state) {\r\n        if (this._state === state) {\r\n            return;\r\n        }\r\n        switch (state) {\r\n            case \"canceling\" /* InternalTaskState.CANCELING */:\r\n            case \"pausing\" /* InternalTaskState.PAUSING */:\r\n                // TODO(andysoto):\r\n                // assert(this.state_ === InternalTaskState.RUNNING ||\r\n                //        this.state_ === InternalTaskState.PAUSING);\r\n                this._state = state;\r\n                if (this._request !== undefined) {\r\n                    this._request.cancel();\r\n                }\r\n                else if (this.pendingTimeout) {\r\n                    clearTimeout(this.pendingTimeout);\r\n                    this.pendingTimeout = undefined;\r\n                    this.completeTransitions_();\r\n                }\r\n                break;\r\n            case \"running\" /* InternalTaskState.RUNNING */:\r\n                // TODO(andysoto):\r\n                // assert(this.state_ === InternalTaskState.PAUSED ||\r\n                //        this.state_ === InternalTaskState.PAUSING);\r\n                const wasPaused = this._state === \"paused\" /* InternalTaskState.PAUSED */;\r\n                this._state = state;\r\n                if (wasPaused) {\r\n                    this._notifyObservers();\r\n                    this._start();\r\n                }\r\n                break;\r\n            case \"paused\" /* InternalTaskState.PAUSED */:\r\n                // TODO(andysoto):\r\n                // assert(this.state_ === InternalTaskState.PAUSING);\r\n                this._state = state;\r\n                this._notifyObservers();\r\n                break;\r\n            case \"canceled\" /* InternalTaskState.CANCELED */:\r\n                // TODO(andysoto):\r\n                // assert(this.state_ === InternalTaskState.PAUSED ||\r\n                //        this.state_ === InternalTaskState.CANCELING);\r\n                this._error = canceled();\r\n                this._state = state;\r\n                this._notifyObservers();\r\n                break;\r\n            case \"error\" /* InternalTaskState.ERROR */:\r\n                // TODO(andysoto):\r\n                // assert(this.state_ === InternalTaskState.RUNNING ||\r\n                //        this.state_ === InternalTaskState.PAUSING ||\r\n                //        this.state_ === InternalTaskState.CANCELING);\r\n                this._state = state;\r\n                this._notifyObservers();\r\n                break;\r\n            case \"success\" /* InternalTaskState.SUCCESS */:\r\n                // TODO(andysoto):\r\n                // assert(this.state_ === InternalTaskState.RUNNING ||\r\n                //        this.state_ === InternalTaskState.PAUSING ||\r\n                //        this.state_ === InternalTaskState.CANCELING);\r\n                this._state = state;\r\n                this._notifyObservers();\r\n                break;\r\n        }\r\n    }\r\n    completeTransitions_() {\r\n        switch (this._state) {\r\n            case \"pausing\" /* InternalTaskState.PAUSING */:\r\n                this._transition(\"paused\" /* InternalTaskState.PAUSED */);\r\n                break;\r\n            case \"canceling\" /* InternalTaskState.CANCELING */:\r\n                this._transition(\"canceled\" /* InternalTaskState.CANCELED */);\r\n                break;\r\n            case \"running\" /* InternalTaskState.RUNNING */:\r\n                this._start();\r\n                break;\r\n        }\r\n    }\r\n    /**\r\n     * A snapshot of the current task state.\r\n     */\r\n    get snapshot() {\r\n        const externalState = taskStateFromInternalTaskState(this._state);\r\n        return {\r\n            bytesTransferred: this._transferred,\r\n            totalBytes: this._blob.size(),\r\n            state: externalState,\r\n            metadata: this._metadata,\r\n            task: this,\r\n            ref: this._ref\r\n        };\r\n    }\r\n    /**\r\n     * Adds a callback for an event.\r\n     * @param type - The type of event to listen for.\r\n     * @param nextOrObserver -\r\n     *     The `next` function, which gets called for each item in\r\n     *     the event stream, or an observer object with some or all of these three\r\n     *     properties (`next`, `error`, `complete`).\r\n     * @param error - A function that gets called with a `StorageError`\r\n     *     if the event stream ends due to an error.\r\n     * @param completed - A function that gets called if the\r\n     *     event stream ends normally.\r\n     * @returns\r\n     *     If only the event argument is passed, returns a function you can use to\r\n     *     add callbacks (see the examples above). If more than just the event\r\n     *     argument is passed, returns a function you can call to unregister the\r\n     *     callbacks.\r\n     */\r\n    on(type, nextOrObserver, error, completed) {\r\n        // Note: `type` isn't being used. Its type is also incorrect. TaskEvent should not be a string.\r\n        const observer = new Observer(nextOrObserver || undefined, error || undefined, completed || undefined);\r\n        this._addObserver(observer);\r\n        return () => {\r\n            this._removeObserver(observer);\r\n        };\r\n    }\r\n    /**\r\n     * This object behaves like a Promise, and resolves with its snapshot data\r\n     * when the upload completes.\r\n     * @param onFulfilled - The fulfillment callback. Promise chaining works as normal.\r\n     * @param onRejected - The rejection callback.\r\n     */\r\n    then(onFulfilled, onRejected) {\r\n        // These casts are needed so that TypeScript can infer the types of the\r\n        // resulting Promise.\r\n        return this._promise.then(onFulfilled, onRejected);\r\n    }\r\n    /**\r\n     * Equivalent to calling `then(null, onRejected)`.\r\n     */\r\n    catch(onRejected) {\r\n        return this.then(null, onRejected);\r\n    }\r\n    /**\r\n     * Adds the given observer.\r\n     */\r\n    _addObserver(observer) {\r\n        this._observers.push(observer);\r\n        this._notifyObserver(observer);\r\n    }\r\n    /**\r\n     * Removes the given observer.\r\n     */\r\n    _removeObserver(observer) {\r\n        const i = this._observers.indexOf(observer);\r\n        if (i !== -1) {\r\n            this._observers.splice(i, 1);\r\n        }\r\n    }\r\n    _notifyObservers() {\r\n        this._finishPromise();\r\n        const observers = this._observers.slice();\r\n        observers.forEach(observer => {\r\n            this._notifyObserver(observer);\r\n        });\r\n    }\r\n    _finishPromise() {\r\n        if (this._resolve !== undefined) {\r\n            let triggered = true;\r\n            switch (taskStateFromInternalTaskState(this._state)) {\r\n                case TaskState.SUCCESS:\r\n                    async(this._resolve.bind(null, this.snapshot))();\r\n                    break;\r\n                case TaskState.CANCELED:\r\n                case TaskState.ERROR:\r\n                    const toCall = this._reject;\r\n                    async(toCall.bind(null, this._error))();\r\n                    break;\r\n                default:\r\n                    triggered = false;\r\n                    break;\r\n            }\r\n            if (triggered) {\r\n                this._resolve = undefined;\r\n                this._reject = undefined;\r\n            }\r\n        }\r\n    }\r\n    _notifyObserver(observer) {\r\n        const externalState = taskStateFromInternalTaskState(this._state);\r\n        switch (externalState) {\r\n            case TaskState.RUNNING:\r\n            case TaskState.PAUSED:\r\n                if (observer.next) {\r\n                    async(observer.next.bind(observer, this.snapshot))();\r\n                }\r\n                break;\r\n            case TaskState.SUCCESS:\r\n                if (observer.complete) {\r\n                    async(observer.complete.bind(observer))();\r\n                }\r\n                break;\r\n            case TaskState.CANCELED:\r\n            case TaskState.ERROR:\r\n                if (observer.error) {\r\n                    async(observer.error.bind(observer, this._error))();\r\n                }\r\n                break;\r\n            default:\r\n                // TODO(andysoto): assert(false);\r\n                if (observer.error) {\r\n                    async(observer.error.bind(observer, this._error))();\r\n                }\r\n        }\r\n    }\r\n    /**\r\n     * Resumes a paused task. Has no effect on a currently running or failed task.\r\n     * @returns True if the operation took effect, false if ignored.\r\n     */\r\n    resume() {\r\n        const valid = this._state === \"paused\" /* InternalTaskState.PAUSED */ ||\r\n            this._state === \"pausing\" /* InternalTaskState.PAUSING */;\r\n        if (valid) {\r\n            this._transition(\"running\" /* InternalTaskState.RUNNING */);\r\n        }\r\n        return valid;\r\n    }\r\n    /**\r\n     * Pauses a currently running task. Has no effect on a paused or failed task.\r\n     * @returns True if the operation took effect, false if ignored.\r\n     */\r\n    pause() {\r\n        const valid = this._state === \"running\" /* InternalTaskState.RUNNING */;\r\n        if (valid) {\r\n            this._transition(\"pausing\" /* InternalTaskState.PAUSING */);\r\n        }\r\n        return valid;\r\n    }\r\n    /**\r\n     * Cancels a currently running or paused task. Has no effect on a complete or\r\n     * failed task.\r\n     * @returns True if the operation took effect, false if ignored.\r\n     */\r\n    cancel() {\r\n        const valid = this._state === \"running\" /* InternalTaskState.RUNNING */ ||\r\n            this._state === \"pausing\" /* InternalTaskState.PAUSING */;\r\n        if (valid) {\r\n            this._transition(\"canceling\" /* InternalTaskState.CANCELING */);\r\n        }\r\n        return valid;\r\n    }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provides methods to interact with a bucket in the Firebase Storage service.\r\n * @internal\r\n * @param _location - An fbs.location, or the URL at\r\n *     which to base this object, in one of the following forms:\r\n *         gs://<bucket>/<object-path>\r\n *         http[s]://firebasestorage.googleapis.com/\r\n *                     <api-version>/b/<bucket>/o/<object-path>\r\n *     Any query or fragment strings will be ignored in the http[s]\r\n *     format. If no value is passed, the storage object will use a URL based on\r\n *     the project ID of the base firebase.App instance.\r\n */\r\nclass Reference {\r\n    constructor(_service, location) {\r\n        this._service = _service;\r\n        if (location instanceof Location) {\r\n            this._location = location;\r\n        }\r\n        else {\r\n            this._location = Location.makeFromUrl(location, _service.host);\r\n        }\r\n    }\r\n    /**\r\n     * Returns the URL for the bucket and path this object references,\r\n     *     in the form gs://<bucket>/<object-path>\r\n     * @override\r\n     */\r\n    toString() {\r\n        return 'gs://' + this._location.bucket + '/' + this._location.path;\r\n    }\r\n    _newRef(service, location) {\r\n        return new Reference(service, location);\r\n    }\r\n    /**\r\n     * A reference to the root of this object's bucket.\r\n     */\r\n    get root() {\r\n        const location = new Location(this._location.bucket, '');\r\n        return this._newRef(this._service, location);\r\n    }\r\n    /**\r\n     * The name of the bucket containing this reference's object.\r\n     */\r\n    get bucket() {\r\n        return this._location.bucket;\r\n    }\r\n    /**\r\n     * The full path of this object.\r\n     */\r\n    get fullPath() {\r\n        return this._location.path;\r\n    }\r\n    /**\r\n     * The short name of this object, which is the last component of the full path.\r\n     * For example, if fullPath is 'full/path/image.png', name is 'image.png'.\r\n     */\r\n    get name() {\r\n        return lastComponent(this._location.path);\r\n    }\r\n    /**\r\n     * The `StorageService` instance this `StorageReference` is associated with.\r\n     */\r\n    get storage() {\r\n        return this._service;\r\n    }\r\n    /**\r\n     * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if\r\n     * this reference is the root.\r\n     */\r\n    get parent() {\r\n        const newPath = parent(this._location.path);\r\n        if (newPath === null) {\r\n            return null;\r\n        }\r\n        const location = new Location(this._location.bucket, newPath);\r\n        return new Reference(this._service, location);\r\n    }\r\n    /**\r\n     * Utility function to throw an error in methods that do not accept a root reference.\r\n     */\r\n    _throwIfRoot(name) {\r\n        if (this._location.path === '') {\r\n            throw invalidRootOperation(name);\r\n        }\r\n    }\r\n}\r\n/**\r\n * Download the bytes at the object's location.\r\n * @returns A Promise containing the downloaded bytes.\r\n */\r\nfunction getBytesInternal(ref, maxDownloadSizeBytes) {\r\n    ref._throwIfRoot('getBytes');\r\n    const requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);\r\n    return ref.storage\r\n        .makeRequestWithTokens(requestInfo, newBytesConnection)\r\n        .then(bytes => maxDownloadSizeBytes !== undefined\r\n        ? // GCS may not honor the Range header for small files\r\n            bytes.slice(0, maxDownloadSizeBytes)\r\n        : bytes);\r\n}\r\n/**\r\n * Download the bytes at the object's location.\r\n * @returns A Promise containing the downloaded blob.\r\n */\r\nfunction getBlobInternal(ref, maxDownloadSizeBytes) {\r\n    ref._throwIfRoot('getBlob');\r\n    const requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);\r\n    return ref.storage\r\n        .makeRequestWithTokens(requestInfo, newBlobConnection)\r\n        .then(blob => maxDownloadSizeBytes !== undefined\r\n        ? // GCS may not honor the Range header for small files\r\n            blob.slice(0, maxDownloadSizeBytes)\r\n        : blob);\r\n}\r\n/**\r\n * Uploads data to this object's location.\r\n * The upload is not resumable.\r\n *\r\n * @param ref - StorageReference where data should be uploaded.\r\n * @param data - The data to upload.\r\n * @param metadata - Metadata for the newly uploaded data.\r\n * @returns A Promise containing an UploadResult\r\n */\r\nfunction uploadBytes$1(ref, data, metadata) {\r\n    ref._throwIfRoot('uploadBytes');\r\n    const requestInfo = multipartUpload(ref.storage, ref._location, getMappings(), new FbsBlob(data, true), metadata);\r\n    return ref.storage\r\n        .makeRequestWithTokens(requestInfo, newTextConnection)\r\n        .then(finalMetadata => {\r\n        return {\r\n            metadata: finalMetadata,\r\n            ref\r\n        };\r\n    });\r\n}\r\n/**\r\n * Uploads data to this object's location.\r\n * The upload can be paused and resumed, and exposes progress updates.\r\n * @public\r\n * @param ref - StorageReference where data should be uploaded.\r\n * @param data - The data to upload.\r\n * @param metadata - Metadata for the newly uploaded data.\r\n * @returns An UploadTask\r\n */\r\nfunction uploadBytesResumable$1(ref, data, metadata) {\r\n    ref._throwIfRoot('uploadBytesResumable');\r\n    return new UploadTask(ref, new FbsBlob(data), metadata);\r\n}\r\n/**\r\n * Uploads a string to this object's location.\r\n * The upload is not resumable.\r\n * @public\r\n * @param ref - StorageReference where string should be uploaded.\r\n * @param value - The string to upload.\r\n * @param format - The format of the string to upload.\r\n * @param metadata - Metadata for the newly uploaded string.\r\n * @returns A Promise containing an UploadResult\r\n */\r\nfunction uploadString$1(ref, value, format = StringFormat.RAW, metadata) {\r\n    ref._throwIfRoot('uploadString');\r\n    const data = dataFromString(format, value);\r\n    const metadataClone = Object.assign({}, metadata);\r\n    if (metadataClone['contentType'] == null && data.contentType != null) {\r\n        metadataClone['contentType'] = data.contentType;\r\n    }\r\n    return uploadBytes$1(ref, data.data, metadataClone);\r\n}\r\n/**\r\n * List all items (files) and prefixes (folders) under this storage reference.\r\n *\r\n * This is a helper method for calling list() repeatedly until there are\r\n * no more results. The default pagination size is 1000.\r\n *\r\n * Note: The results may not be consistent if objects are changed while this\r\n * operation is running.\r\n *\r\n * Warning: listAll may potentially consume too many resources if there are\r\n * too many results.\r\n * @public\r\n * @param ref - StorageReference to get list from.\r\n *\r\n * @returns A Promise that resolves with all the items and prefixes under\r\n *      the current storage reference. `prefixes` contains references to\r\n *      sub-directories and `items` contains references to objects in this\r\n *      folder. `nextPageToken` is never returned.\r\n */\r\nfunction listAll$1(ref) {\r\n    const accumulator = {\r\n        prefixes: [],\r\n        items: []\r\n    };\r\n    return listAllHelper(ref, accumulator).then(() => accumulator);\r\n}\r\n/**\r\n * Separated from listAll because async functions can't use \"arguments\".\r\n * @param ref\r\n * @param accumulator\r\n * @param pageToken\r\n */\r\nasync function listAllHelper(ref, accumulator, pageToken) {\r\n    const opt = {\r\n        // maxResults is 1000 by default.\r\n        pageToken\r\n    };\r\n    const nextPage = await list$1(ref, opt);\r\n    accumulator.prefixes.push(...nextPage.prefixes);\r\n    accumulator.items.push(...nextPage.items);\r\n    if (nextPage.nextPageToken != null) {\r\n        await listAllHelper(ref, accumulator, nextPage.nextPageToken);\r\n    }\r\n}\r\n/**\r\n * List items (files) and prefixes (folders) under this storage reference.\r\n *\r\n * List API is only available for Firebase Rules Version 2.\r\n *\r\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\r\n * delimited folder structure.\r\n * Refer to GCS's List API if you want to learn more.\r\n *\r\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\r\n * support objects whose paths end with \"/\" or contain two consecutive\r\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\r\n * list() may fail if there are too many unsupported objects in the bucket.\r\n * @public\r\n *\r\n * @param ref - StorageReference to get list from.\r\n * @param options - See ListOptions for details.\r\n * @returns A Promise that resolves with the items and prefixes.\r\n *      `prefixes` contains references to sub-folders and `items`\r\n *      contains references to objects in this folder. `nextPageToken`\r\n *      can be used to get the rest of the results.\r\n */\r\nfunction list$1(ref, options) {\r\n    if (options != null) {\r\n        if (typeof options.maxResults === 'number') {\r\n            validateNumber('options.maxResults', \r\n            /* minValue= */ 1, \r\n            /* maxValue= */ 1000, options.maxResults);\r\n        }\r\n    }\r\n    const op = options || {};\r\n    const requestInfo = list$2(ref.storage, ref._location, \r\n    /*delimiter= */ '/', op.pageToken, op.maxResults);\r\n    return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\r\n}\r\n/**\r\n * A `Promise` that resolves with the metadata for this object. If this\r\n * object doesn't exist or metadata cannot be retreived, the promise is\r\n * rejected.\r\n * @public\r\n * @param ref - StorageReference to get metadata from.\r\n */\r\nfunction getMetadata$1(ref) {\r\n    ref._throwIfRoot('getMetadata');\r\n    const requestInfo = getMetadata$2(ref.storage, ref._location, getMappings());\r\n    return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\r\n}\r\n/**\r\n * Updates the metadata for this object.\r\n * @public\r\n * @param ref - StorageReference to update metadata for.\r\n * @param metadata - The new metadata for the object.\r\n *     Only values that have been explicitly set will be changed. Explicitly\r\n *     setting a value to null will remove the metadata.\r\n * @returns A `Promise` that resolves\r\n *     with the new metadata for this object.\r\n *     See `firebaseStorage.Reference.prototype.getMetadata`\r\n */\r\nfunction updateMetadata$1(ref, metadata) {\r\n    ref._throwIfRoot('updateMetadata');\r\n    const requestInfo = updateMetadata$2(ref.storage, ref._location, metadata, getMappings());\r\n    return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\r\n}\r\n/**\r\n * Returns the download URL for the given Reference.\r\n * @public\r\n * @returns A `Promise` that resolves with the download\r\n *     URL for this object.\r\n */\r\nfunction getDownloadURL$1(ref) {\r\n    ref._throwIfRoot('getDownloadURL');\r\n    const requestInfo = getDownloadUrl(ref.storage, ref._location, getMappings());\r\n    return ref.storage\r\n        .makeRequestWithTokens(requestInfo, newTextConnection)\r\n        .then(url => {\r\n        if (url === null) {\r\n            throw noDownloadURL();\r\n        }\r\n        return url;\r\n    });\r\n}\r\n/**\r\n * Deletes the object at this location.\r\n * @public\r\n * @param ref - StorageReference for object to delete.\r\n * @returns A `Promise` that resolves if the deletion succeeds.\r\n */\r\nfunction deleteObject$1(ref) {\r\n    ref._throwIfRoot('deleteObject');\r\n    const requestInfo = deleteObject$2(ref.storage, ref._location);\r\n    return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\r\n}\r\n/**\r\n * Returns reference for object obtained by appending `childPath` to `ref`.\r\n *\r\n * @param ref - StorageReference to get child of.\r\n * @param childPath - Child path from provided ref.\r\n * @returns A reference to the object obtained by\r\n * appending childPath, removing any duplicate, beginning, or trailing\r\n * slashes.\r\n *\r\n */\r\nfunction _getChild$1(ref, childPath) {\r\n    const newPath = child(ref._location.path, childPath);\r\n    const location = new Location(ref._location.bucket, newPath);\r\n    return new Reference(ref.storage, location);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isUrl(path) {\r\n    return /^[A-Za-z]+:\\/\\//.test(path);\r\n}\r\n/**\r\n * Returns a firebaseStorage.Reference for the given url.\r\n */\r\nfunction refFromURL(service, url) {\r\n    return new Reference(service, url);\r\n}\r\n/**\r\n * Returns a firebaseStorage.Reference for the given path in the default\r\n * bucket.\r\n */\r\nfunction refFromPath(ref, path) {\r\n    if (ref instanceof FirebaseStorageImpl) {\r\n        const service = ref;\r\n        if (service._bucket == null) {\r\n            throw noDefaultBucket();\r\n        }\r\n        const reference = new Reference(service, service._bucket);\r\n        if (path != null) {\r\n            return refFromPath(reference, path);\r\n        }\r\n        else {\r\n            return reference;\r\n        }\r\n    }\r\n    else {\r\n        // ref is a Reference\r\n        if (path !== undefined) {\r\n            return _getChild$1(ref, path);\r\n        }\r\n        else {\r\n            return ref;\r\n        }\r\n    }\r\n}\r\nfunction ref$1(serviceOrRef, pathOrUrl) {\r\n    if (pathOrUrl && isUrl(pathOrUrl)) {\r\n        if (serviceOrRef instanceof FirebaseStorageImpl) {\r\n            return refFromURL(serviceOrRef, pathOrUrl);\r\n        }\r\n        else {\r\n            throw invalidArgument('To use ref(service, url), the first argument must be a Storage instance.');\r\n        }\r\n    }\r\n    else {\r\n        return refFromPath(serviceOrRef, pathOrUrl);\r\n    }\r\n}\r\nfunction extractBucket(host, config) {\r\n    const bucketString = config === null || config === void 0 ? void 0 : config[CONFIG_STORAGE_BUCKET_KEY];\r\n    if (bucketString == null) {\r\n        return null;\r\n    }\r\n    return Location.makeFromBucketSpec(bucketString, host);\r\n}\r\nfunction connectStorageEmulator$1(storage, host, port, options = {}) {\r\n    storage.host = `${host}:${port}`;\r\n    storage._protocol = 'http';\r\n    const { mockUserToken } = options;\r\n    if (mockUserToken) {\r\n        storage._overrideAuthToken =\r\n            typeof mockUserToken === 'string'\r\n                ? mockUserToken\r\n                : createMockUserToken(mockUserToken, storage.app.options.projectId);\r\n    }\r\n}\r\n/**\r\n * A service that provides Firebase Storage Reference instances.\r\n * @param opt_url - gs:// url to a custom Storage Bucket\r\n *\r\n * @internal\r\n */\r\nclass FirebaseStorageImpl {\r\n    constructor(\r\n    /**\r\n     * FirebaseApp associated with this StorageService instance.\r\n     */\r\n    app, _authProvider, \r\n    /**\r\n     * @internal\r\n     */\r\n    _appCheckProvider, \r\n    /**\r\n     * @internal\r\n     */\r\n    _url, _firebaseVersion) {\r\n        this.app = app;\r\n        this._authProvider = _authProvider;\r\n        this._appCheckProvider = _appCheckProvider;\r\n        this._url = _url;\r\n        this._firebaseVersion = _firebaseVersion;\r\n        this._bucket = null;\r\n        /**\r\n         * This string can be in the formats:\r\n         * - host\r\n         * - host:port\r\n         */\r\n        this._host = DEFAULT_HOST;\r\n        this._protocol = 'https';\r\n        this._appId = null;\r\n        this._deleted = false;\r\n        this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;\r\n        this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;\r\n        this._requests = new Set();\r\n        if (_url != null) {\r\n            this._bucket = Location.makeFromBucketSpec(_url, this._host);\r\n        }\r\n        else {\r\n            this._bucket = extractBucket(this._host, this.app.options);\r\n        }\r\n    }\r\n    /**\r\n     * The host string for this service, in the form of `host` or\r\n     * `host:port`.\r\n     */\r\n    get host() {\r\n        return this._host;\r\n    }\r\n    set host(host) {\r\n        this._host = host;\r\n        if (this._url != null) {\r\n            this._bucket = Location.makeFromBucketSpec(this._url, host);\r\n        }\r\n        else {\r\n            this._bucket = extractBucket(host, this.app.options);\r\n        }\r\n    }\r\n    /**\r\n     * The maximum time to retry uploads in milliseconds.\r\n     */\r\n    get maxUploadRetryTime() {\r\n        return this._maxUploadRetryTime;\r\n    }\r\n    set maxUploadRetryTime(time) {\r\n        validateNumber('time', \r\n        /* minValue=*/ 0, \r\n        /* maxValue= */ Number.POSITIVE_INFINITY, time);\r\n        this._maxUploadRetryTime = time;\r\n    }\r\n    /**\r\n     * The maximum time to retry operations other than uploads or downloads in\r\n     * milliseconds.\r\n     */\r\n    get maxOperationRetryTime() {\r\n        return this._maxOperationRetryTime;\r\n    }\r\n    set maxOperationRetryTime(time) {\r\n        validateNumber('time', \r\n        /* minValue=*/ 0, \r\n        /* maxValue= */ Number.POSITIVE_INFINITY, time);\r\n        this._maxOperationRetryTime = time;\r\n    }\r\n    async _getAuthToken() {\r\n        if (this._overrideAuthToken) {\r\n            return this._overrideAuthToken;\r\n        }\r\n        const auth = this._authProvider.getImmediate({ optional: true });\r\n        if (auth) {\r\n            const tokenData = await auth.getToken();\r\n            if (tokenData !== null) {\r\n                return tokenData.accessToken;\r\n            }\r\n        }\r\n        return null;\r\n    }\r\n    async _getAppCheckToken() {\r\n        const appCheck = this._appCheckProvider.getImmediate({ optional: true });\r\n        if (appCheck) {\r\n            const result = await appCheck.getToken();\r\n            // TODO: What do we want to do if there is an error getting the token?\r\n            // Context: appCheck.getToken() will never throw even if an error happened. In the error case, a dummy token will be\r\n            // returned along with an error field describing the error. In general, we shouldn't care about the error condition and just use\r\n            // the token (actual or dummy) to send requests.\r\n            return result.token;\r\n        }\r\n        return null;\r\n    }\r\n    /**\r\n     * Stop running requests and prevent more from being created.\r\n     */\r\n    _delete() {\r\n        if (!this._deleted) {\r\n            this._deleted = true;\r\n            this._requests.forEach(request => request.cancel());\r\n            this._requests.clear();\r\n        }\r\n        return Promise.resolve();\r\n    }\r\n    /**\r\n     * Returns a new firebaseStorage.Reference object referencing this StorageService\r\n     * at the given Location.\r\n     */\r\n    _makeStorageReference(loc) {\r\n        return new Reference(this, loc);\r\n    }\r\n    /**\r\n     * @param requestInfo - HTTP RequestInfo object\r\n     * @param authToken - Firebase auth token\r\n     */\r\n    _makeRequest(requestInfo, requestFactory, authToken, appCheckToken, retry = true) {\r\n        if (!this._deleted) {\r\n            const request = makeRequest(requestInfo, this._appId, authToken, appCheckToken, requestFactory, this._firebaseVersion, retry);\r\n            this._requests.add(request);\r\n            // Request removes itself from set when complete.\r\n            request.getPromise().then(() => this._requests.delete(request), () => this._requests.delete(request));\r\n            return request;\r\n        }\r\n        else {\r\n            return new FailRequest(appDeleted());\r\n        }\r\n    }\r\n    async makeRequestWithTokens(requestInfo, requestFactory) {\r\n        const [authToken, appCheckToken] = await Promise.all([\r\n            this._getAuthToken(),\r\n            this._getAppCheckToken()\r\n        ]);\r\n        return this._makeRequest(requestInfo, requestFactory, authToken, appCheckToken).getPromise();\r\n    }\r\n}\n\nconst name = \"@firebase/storage\";\nconst version = \"0.11.2\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Type constant for Firebase Storage.\r\n */\r\nconst STORAGE_TYPE = 'storage';\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Downloads the data at the object's location. Returns an error if the object\r\n * is not found.\r\n *\r\n * To use this functionality, you have to whitelist your app's origin in your\r\n * Cloud Storage bucket. See also\r\n * https://cloud.google.com/storage/docs/configuring-cors\r\n *\r\n * @public\r\n * @param ref - StorageReference where data should be downloaded.\r\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\r\n * retrieve.\r\n * @returns A Promise containing the object's bytes\r\n */\r\nfunction getBytes(ref, maxDownloadSizeBytes) {\r\n    ref = getModularInstance(ref);\r\n    return getBytesInternal(ref, maxDownloadSizeBytes);\r\n}\r\n/**\r\n * Uploads data to this object's location.\r\n * The upload is not resumable.\r\n * @public\r\n * @param ref - {@link StorageReference} where data should be uploaded.\r\n * @param data - The data to upload.\r\n * @param metadata - Metadata for the data to upload.\r\n * @returns A Promise containing an UploadResult\r\n */\r\nfunction uploadBytes(ref, data, metadata) {\r\n    ref = getModularInstance(ref);\r\n    return uploadBytes$1(ref, data, metadata);\r\n}\r\n/**\r\n * Uploads a string to this object's location.\r\n * The upload is not resumable.\r\n * @public\r\n * @param ref - {@link StorageReference} where string should be uploaded.\r\n * @param value - The string to upload.\r\n * @param format - The format of the string to upload.\r\n * @param metadata - Metadata for the string to upload.\r\n * @returns A Promise containing an UploadResult\r\n */\r\nfunction uploadString(ref, value, format, metadata) {\r\n    ref = getModularInstance(ref);\r\n    return uploadString$1(ref, value, format, metadata);\r\n}\r\n/**\r\n * Uploads data to this object's location.\r\n * The upload can be paused and resumed, and exposes progress updates.\r\n * @public\r\n * @param ref - {@link StorageReference} where data should be uploaded.\r\n * @param data - The data to upload.\r\n * @param metadata - Metadata for the data to upload.\r\n * @returns An UploadTask\r\n */\r\nfunction uploadBytesResumable(ref, data, metadata) {\r\n    ref = getModularInstance(ref);\r\n    return uploadBytesResumable$1(ref, data, metadata);\r\n}\r\n/**\r\n * A `Promise` that resolves with the metadata for this object. If this\r\n * object doesn't exist or metadata cannot be retreived, the promise is\r\n * rejected.\r\n * @public\r\n * @param ref - {@link StorageReference} to get metadata from.\r\n */\r\nfunction getMetadata(ref) {\r\n    ref = getModularInstance(ref);\r\n    return getMetadata$1(ref);\r\n}\r\n/**\r\n * Updates the metadata for this object.\r\n * @public\r\n * @param ref - {@link StorageReference} to update metadata for.\r\n * @param metadata - The new metadata for the object.\r\n *     Only values that have been explicitly set will be changed. Explicitly\r\n *     setting a value to null will remove the metadata.\r\n * @returns A `Promise` that resolves with the new metadata for this object.\r\n */\r\nfunction updateMetadata(ref, metadata) {\r\n    ref = getModularInstance(ref);\r\n    return updateMetadata$1(ref, metadata);\r\n}\r\n/**\r\n * List items (files) and prefixes (folders) under this storage reference.\r\n *\r\n * List API is only available for Firebase Rules Version 2.\r\n *\r\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\r\n * delimited folder structure.\r\n * Refer to GCS's List API if you want to learn more.\r\n *\r\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\r\n * support objects whose paths end with \"/\" or contain two consecutive\r\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\r\n * list() may fail if there are too many unsupported objects in the bucket.\r\n * @public\r\n *\r\n * @param ref - {@link StorageReference} to get list from.\r\n * @param options - See {@link ListOptions} for details.\r\n * @returns A `Promise` that resolves with the items and prefixes.\r\n *      `prefixes` contains references to sub-folders and `items`\r\n *      contains references to objects in this folder. `nextPageToken`\r\n *      can be used to get the rest of the results.\r\n */\r\nfunction list(ref, options) {\r\n    ref = getModularInstance(ref);\r\n    return list$1(ref, options);\r\n}\r\n/**\r\n * List all items (files) and prefixes (folders) under this storage reference.\r\n *\r\n * This is a helper method for calling list() repeatedly until there are\r\n * no more results. The default pagination size is 1000.\r\n *\r\n * Note: The results may not be consistent if objects are changed while this\r\n * operation is running.\r\n *\r\n * Warning: `listAll` may potentially consume too many resources if there are\r\n * too many results.\r\n * @public\r\n * @param ref - {@link StorageReference} to get list from.\r\n *\r\n * @returns A `Promise` that resolves with all the items and prefixes under\r\n *      the current storage reference. `prefixes` contains references to\r\n *      sub-directories and `items` contains references to objects in this\r\n *      folder. `nextPageToken` is never returned.\r\n */\r\nfunction listAll(ref) {\r\n    ref = getModularInstance(ref);\r\n    return listAll$1(ref);\r\n}\r\n/**\r\n * Returns the download URL for the given {@link StorageReference}.\r\n * @public\r\n * @param ref - {@link StorageReference} to get the download URL for.\r\n * @returns A `Promise` that resolves with the download\r\n *     URL for this object.\r\n */\r\nfunction getDownloadURL(ref) {\r\n    ref = getModularInstance(ref);\r\n    return getDownloadURL$1(ref);\r\n}\r\n/**\r\n * Deletes the object at this location.\r\n * @public\r\n * @param ref - {@link StorageReference} for object to delete.\r\n * @returns A `Promise` that resolves if the deletion succeeds.\r\n */\r\nfunction deleteObject(ref) {\r\n    ref = getModularInstance(ref);\r\n    return deleteObject$1(ref);\r\n}\r\nfunction ref(serviceOrRef, pathOrUrl) {\r\n    serviceOrRef = getModularInstance(serviceOrRef);\r\n    return ref$1(serviceOrRef, pathOrUrl);\r\n}\r\n/**\r\n * @internal\r\n */\r\nfunction _getChild(ref, childPath) {\r\n    return _getChild$1(ref, childPath);\r\n}\r\n/**\r\n * Gets a {@link FirebaseStorage} instance for the given Firebase app.\r\n * @public\r\n * @param app - Firebase app to get {@link FirebaseStorage} instance for.\r\n * @param bucketUrl - The gs:// url to your Firebase Storage Bucket.\r\n * If not passed, uses the app's default Storage Bucket.\r\n * @returns A {@link FirebaseStorage} instance.\r\n */\r\nfunction getStorage(app = getApp(), bucketUrl) {\r\n    app = getModularInstance(app);\r\n    const storageProvider = _getProvider(app, STORAGE_TYPE);\r\n    const storageInstance = storageProvider.getImmediate({\r\n        identifier: bucketUrl\r\n    });\r\n    const emulator = getDefaultEmulatorHostnameAndPort('storage');\r\n    if (emulator) {\r\n        connectStorageEmulator(storageInstance, ...emulator);\r\n    }\r\n    return storageInstance;\r\n}\r\n/**\r\n * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.\r\n *\r\n * @param storage - The {@link FirebaseStorage} instance\r\n * @param host - The emulator host (ex: localhost)\r\n * @param port - The emulator port (ex: 5001)\r\n * @param options - Emulator options. `options.mockUserToken` is the mock auth\r\n * token to use for unit testing Security Rules.\r\n * @public\r\n */\r\nfunction connectStorageEmulator(storage, host, port, options = {}) {\r\n    connectStorageEmulator$1(storage, host, port, options);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *   http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Downloads the data at the object's location. Returns an error if the object\r\n * is not found.\r\n *\r\n * To use this functionality, you have to whitelist your app's origin in your\r\n * Cloud Storage bucket. See also\r\n * https://cloud.google.com/storage/docs/configuring-cors\r\n *\r\n * This API is not available in Node.\r\n *\r\n * @public\r\n * @param ref - StorageReference where data should be downloaded.\r\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\r\n * retrieve.\r\n * @returns A Promise that resolves with a Blob containing the object's bytes\r\n */\r\nfunction getBlob(ref, maxDownloadSizeBytes) {\r\n    ref = getModularInstance(ref);\r\n    return getBlobInternal(ref, maxDownloadSizeBytes);\r\n}\r\n/**\r\n * Downloads the data at the object's location. Raises an error event if the\r\n * object is not found.\r\n *\r\n * This API is only available in Node.\r\n *\r\n * @public\r\n * @param ref - StorageReference where data should be downloaded.\r\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\r\n * retrieve.\r\n * @returns A stream with the object's data as bytes\r\n */\r\nfunction getStream(ref, maxDownloadSizeBytes) {\r\n    throw new Error('getStream() is only supported by NodeJS builds');\r\n}\n\n/**\r\n * Cloud Storage for Firebase\r\n *\r\n * @packageDocumentation\r\n */\r\nfunction factory(container, { instanceIdentifier: url }) {\r\n    const app = container.getProvider('app').getImmediate();\r\n    const authProvider = container.getProvider('auth-internal');\r\n    const appCheckProvider = container.getProvider('app-check-internal');\r\n    return new FirebaseStorageImpl(app, authProvider, appCheckProvider, url, SDK_VERSION);\r\n}\r\nfunction registerStorage() {\r\n    _registerComponent(new Component(STORAGE_TYPE, factory, \"PUBLIC\" /* ComponentType.PUBLIC */).setMultipleInstances(true));\r\n    //RUNTIME_ENV will be replaced during the compilation to \"node\" for nodejs and an empty string for browser\r\n    registerVersion(name, version, '');\r\n    // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n    registerVersion(name, version, 'esm2017');\r\n}\r\nregisterStorage();\n\nexport { StorageError, StorageErrorCode, StringFormat, FbsBlob as _FbsBlob, Location as _Location, TaskEvent as _TaskEvent, TaskState as _TaskState, UploadTask as _UploadTask, dataFromString as _dataFromString, _getChild, invalidArgument as _invalidArgument, invalidRootOperation as _invalidRootOperation, connectStorageEmulator, deleteObject, getBlob, getBytes, getDownloadURL, getMetadata, getStorage, getStream, list, listAll, ref, updateMetadata, uploadBytes, uploadBytesResumable, uploadString };\n//# sourceMappingURL=index.esm2017.js.map\n","import {FirebaseApp} from 'firebase/app';\nimport {FirebaseStorage, connectStorageEmulator, getStorage} from 'firebase/storage';\n\nimport {assertDefined} from '../util/asserts';\n\nconst DEV_BUILD = false;\n\nexport class StorageState {\n  private _storage?: FirebaseStorage;\n\n  initialize(app: FirebaseApp) {\n    this._storage = getStorage(app);\n    if (DEV_BUILD) {\n      connectStorageEmulator(this._storage, 'localhost', 9199);\n    }\n  }\n\n  get storage(): FirebaseStorage {\n    return assertDefined(this._storage, 'this._storage');\n  }\n}\n\nexport const STORAGE_STATE = new StorageState();\n","import {FirebaseApp, initializeApp} from 'firebase/app';\n\nimport {AUTH_STATE} from './auth_state';\nimport {FIRESTORE_STATE} from './firestore_state';\nimport {FUNCTIONS_STATE} from './functions_state';\nimport {STORAGE_STATE} from './storage_state';\n\nconst firebaseConfig = {\n  apiKey: 'AIzaSyA_RzCJBYSgXwGj52rqQv8rHsmQ-p02bgc',\n  authDomain: 'fivebit-inventory.firebaseapp.com',\n  projectId: 'fivebit-inventory',\n  storageBucket: 'fivebit-inventory.firebasestorage.app',\n  messagingSenderId: '889074177567',\n  appId: '1:889074177567:web:fa8f4c52ea7d13ad1fa72a',\n  measurementId: 'G-08H52F59YQ',\n};\n\nexport class FirebaseState {\n  private readonly app: FirebaseApp;\n\n  constructor() {\n    this.app = initializeApp(firebaseConfig);\n    FIRESTORE_STATE.initialize(this.app);\n    AUTH_STATE.initialize(this.app);\n    STORAGE_STATE.initialize(this.app);\n    FUNCTIONS_STATE.initialize(this.app);\n  }\n\n  assertInitialized() {\n    // do nothing;\n  }\n}\n\nexport const FIREBASE_STATE = new FirebaseState();\n","import {Commands, RouterLocation} from '@vaadin/router';\nimport {LitElement} from 'lit';\n\nimport {Entity} from '../data/entity';\nimport {AUTH_STATE} from '../firebase/auth_state';\nimport {assertDefined} from '../util/asserts';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Constructor<T> = abstract new (...args: any[]) => T;\n\nexport abstract class BaseElement extends LitElement {\n  private controller: AbortController | null = null;\n\n  listenWhileConnected<T extends keyof HTMLElementEventMap>(\n    type: T,\n    listener: (ev: HTMLElementEventMap[T]) => void,\n  ) {\n    this.addEventListener(type, listener, {\n      signal: assertDefined(\n        this.controller,\n        'called listenWhileConnected before connectedCallback; this.controller',\n      ).signal,\n    });\n  }\n\n  connectedCallback(): void {\n    super.connectedCallback();\n    this.controller = new AbortController();\n  }\n\n  disconnectedCallback(): void {\n    super.disconnectedCallback();\n    assertDefined(this.controller, 'this.controller').abort();\n    this.controller = null;\n  }\n}\n\nexport function RequireLogin<Base extends Constructor<LitElement>>(base: Base) {\n  abstract class RequiresLogin extends base {\n    onBeforeEnter(location: RouterLocation, commands: Commands) {\n      if (AUTH_STATE.currentUser == null) {\n        return commands.redirect('/login?next=' + encodeURIComponent(location.pathname));\n      }\n    }\n  }\n\n  return RequiresLogin;\n}\n\nexport function ListenToEntities<Base extends Constructor<LitElement>>(\n  base: Base,\n  ...propertyNames: string[]\n) {\n  const propertyNamesSet = propertyNames.length > 0 ? new Set(propertyNames) : null;\n\n  abstract class EntityListener extends base {\n    [key: string]: unknown;\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    private listenedEntities = new Set<Entity<any>>();\n\n    update(changes: Map<string, unknown>) {\n      super.update(changes);\n\n      for (const change of changes.keys()) {\n        if (!(propertyNamesSet?.has(change) ?? true)) {\n          continue;\n        }\n        const oldVal = changes.get(change);\n        const newVal = this[change];\n        if (oldVal instanceof Entity) {\n          oldVal.unlisten(this);\n          this.listenedEntities.delete(oldVal);\n        }\n        if (newVal instanceof Entity) {\n          this.listenedEntities.add(newVal);\n          if (this.isConnected) {\n            newVal.listen(this, this.requestUpdate.bind(this));\n          }\n        }\n      }\n    }\n\n    connectedCallback(): void {\n      super.connectedCallback();\n\n      for (const entity of this.listenedEntities) {\n        entity.listen(this, this.requestUpdate.bind(this));\n      }\n    }\n\n    disconnectedCallback(): void {\n      super.disconnectedCallback();\n\n      for (const entity of this.listenedEntities) {\n        entity.unlisten(this);\n      }\n    }\n  }\n\n  return EntityListener;\n}\n","import {DateTime} from 'luxon';\n\nimport {Entry} from '../data/entry';\nimport {FilterFunction} from '../data/filters';\nimport {Tag} from '../data/tags';\n\nexport enum EventType {\n  ADD_FILE = 'addfile',\n  CLOSE_DIALOG = 'closedialog',\n  CLOSE_ENTRY_DETAILS = 'closeentrydetails',\n  CREATE_ENTRY = 'createentry',\n  DATETIME_CHANGE = 'datetimechange',\n  DESCRIPTION_CHANGE = 'descriptionchange',\n  DELETE_ENTRY = 'deleteentry',\n  ENTRY_DRAG_START = 'entrydragstart',\n  ENTRY_DRAG_END = 'entrydragend',\n  HIDE_CREATE_FORM = 'hidecreateform',\n  SET_TITLE = 'settitle',\n  SET_ENTRY_FILTERS = 'setentryfilters',\n  SHOW_CREATE_FORM_AFTER = 'showcreateformafter',\n  SHOW_CREATE_FORM_BEFORE = 'showcreateformbefore',\n  SHOW_ENTRY_DETAILS = 'showentrydetails',\n  TAG_CLICK = 'tagclick',\n  TOGGLE_TAG = 'toggletag',\n}\n\n/**\n * Reusable event which applies to entries, distinguished by event type.\n */\nexport class EntryEvent extends Event {\n  constructor(\n    eventType: EventType,\n    readonly entry: Entry,\n  ) {\n    super(eventType, {bubbles: true, composed: true});\n  }\n}\n\nexport class CreateEntryEvent extends Event {\n  constructor(\n    readonly displayName: string,\n    readonly subsequentEntryId: string | null,\n  ) {\n    super(EventType.CREATE_ENTRY, {bubbles: true, composed: true});\n  }\n}\n\nexport class SetTitleEvent extends Event {\n  constructor(readonly title: string | null) {\n    super(EventType.SET_TITLE, {bubbles: true, composed: true});\n  }\n}\n\nexport class DatetimeChangeEvent extends Event {\n  constructor(\n    readonly datetime: DateTime | null,\n    readonly usesTime: boolean,\n  ) {\n    super(EventType.DATETIME_CHANGE, {bubbles: true, composed: true});\n  }\n}\n\nexport class TagClickEvent extends Event {\n  constructor(readonly tag: Tag) {\n    super(EventType.TAG_CLICK, {bubbles: true, composed: true});\n  }\n}\n\nexport class ToggleTagEvent extends Event {\n  constructor(\n    readonly tag: Tag,\n    readonly enabled: boolean,\n  ) {\n    super(EventType.TOGGLE_TAG, {bubbles: true, composed: true});\n  }\n}\n\nexport class SetEntryFiltersEvent extends Event {\n  constructor(readonly filterFn: FilterFunction) {\n    super(EventType.SET_ENTRY_FILTERS, {bubbles: true, composed: true});\n  }\n}\n\nexport class CloseDialogEvent extends Event {\n  constructor(readonly action: string) {\n    super(EventType.CLOSE_DIALOG, {bubbles: true, composed: true});\n  }\n}\n\ndeclare global {\n  interface HTMLElementEventMap {\n    [EventType.ADD_FILE]: Event;\n    [EventType.CLOSE_DIALOG]: CloseDialogEvent;\n    [EventType.CLOSE_ENTRY_DETAILS]: Event;\n    [EventType.CREATE_ENTRY]: CreateEntryEvent;\n    [EventType.DATETIME_CHANGE]: DatetimeChangeEvent;\n    [EventType.DESCRIPTION_CHANGE]: Event;\n    [EventType.DELETE_ENTRY]: EntryEvent;\n    [EventType.ENTRY_DRAG_START]: EntryEvent;\n    [EventType.ENTRY_DRAG_END]: EntryEvent;\n    [EventType.HIDE_CREATE_FORM]: Event;\n    [EventType.SET_TITLE]: SetTitleEvent;\n    [EventType.SET_ENTRY_FILTERS]: SetEntryFiltersEvent;\n    [EventType.SHOW_CREATE_FORM_AFTER]: EntryEvent;\n    [EventType.SHOW_CREATE_FORM_BEFORE]: EntryEvent;\n    [EventType.SHOW_ENTRY_DETAILS]: EntryEvent;\n    [EventType.TAG_CLICK]: TagClickEvent;\n    [EventType.TOGGLE_TAG]: ToggleTagEvent;\n  }\n}\n","import Bugsnag from '@bugsnag/browser';\nimport {FirebaseError} from '@firebase/util';\nimport {Notification} from '@vaadin/notification';\nimport {Commands, Context, Route, Router} from '@vaadin/router';\nimport {html} from 'lit';\nimport {customElement} from 'lit/decorators.js';\n\nimport {AUTH_STATE} from '../../firebase/auth_state';\nimport {FIREBASE_STATE} from '../../firebase/firebase_state';\nimport {FUNCTIONS_STATE} from '../../firebase/functions_state';\nimport {BaseElement} from '../base';\nimport {EventType, SetTitleEvent} from '../events';\n\nimport styles from './styles.scss';\n\nconst ROUTES: Route[] = [\n  {\n    // Need the .* here to allow for the next= URL param\n    path: '/login(.*)',\n    component: 'inventory-login-view',\n  },\n  {\n    path: '/workspaces',\n    component: 'inventory-workspace-list-view',\n  },\n  {\n    path: '/workspace/:workspaceId/parent/:parentEntryId',\n    component: 'inventory-entry-list-view',\n  },\n  {\n    path: '/workspace/:workspaceId',\n    component: 'inventory-entry-list-view',\n  },\n  {\n    path: '/invite/accept/:workspaceId/:inviteId',\n    async action(context: Context, commands: Commands) {\n      const workspaceId = context.params['workspaceId'] as string;\n      const inviteId = context.params['inviteId'] as string;\n      if (AUTH_STATE.currentUser == null) {\n        return commands.redirect(\n          '/login?next=' + encodeURIComponent(`/invite/accept/${workspaceId}/${inviteId}`),\n        );\n      }\n      try {\n        await FUNCTIONS_STATE.acceptInvite(workspaceId, inviteId);\n        Notification.show('Invite accepted!', {position: 'bottom-center'}).setAttribute(\n          'theme',\n          'success',\n        );\n        return commands.redirect(`/workspace/${workspaceId}`);\n      } catch (e: unknown) {\n        if (e instanceof Error) {\n          Notification.show(`Failed to accept invite: ${e.message}`, {\n            position: 'bottom-center',\n          }).setAttribute('theme', 'error');\n          if (e instanceof FirebaseError && e.code === 'INTERNAL') {\n            Bugsnag.notify(e);\n          }\n        } else {\n          Notification.show(`Failed to accept invite: an unexpected error occurred`, {\n            position: 'bottom-center',\n          }).setAttribute('theme', 'error');\n          const wrapped = new Error('Non-Error error thrown when accepting invite', {cause: e});\n          console.error(wrapped);\n          Bugsnag.notify(wrapped);\n        }\n        return commands.redirect(`/workspaces`);\n      }\n    },\n  },\n  {\n    path: '/invite/reject/:workspaceId/:inviteId',\n    async action(context: Context, commands: Commands) {\n      const workspaceId = context.params['workspaceId'] as string;\n      const inviteId = context.params['inviteId'] as string;\n      if (AUTH_STATE.currentUser == null) {\n        return commands.redirect(\n          '/login?next=' + encodeURIComponent(`/invite/reject/${workspaceId}/${inviteId}`),\n        );\n      }\n      try {\n        await FUNCTIONS_STATE.rejectInvite(workspaceId, inviteId);\n        Notification.show('Invite rejected', {position: 'bottom-center'});\n      } catch (e: unknown) {\n        if (e instanceof Error) {\n          Notification.show(`Failed to reject invite - ${e.message}`, {\n            position: 'bottom-center',\n          }).setAttribute('theme', 'error');\n          if (e instanceof FirebaseError && e.code === 'INTERNAL') {\n            Bugsnag.notify(e);\n          }\n        } else {\n          Notification.show(`Failed to reject invite - an unexpected error occurred`, {\n            position: 'bottom-center',\n          }).setAttribute('theme', 'error');\n          const wrapped = new Error('Non-Error error thrown when rejecting invite', {cause: e});\n          console.error(wrapped);\n          Bugsnag.notify(wrapped);\n        }\n      }\n      return commands.redirect(`/workspaces`);\n    },\n  },\n  {\n    path: '(.*)',\n    action(_context: Context, commands: Commands) {\n      if (AUTH_STATE.currentUser == null) {\n        return commands.redirect('/login');\n      } else {\n        return commands.redirect('/workspaces');\n      }\n    },\n  },\n];\n\nconst BASE_TITLE = 'Five Bit Inventory';\n\n@customElement('inventory-app')\nexport class App extends BaseElement {\n  static styles = styles;\n\n  private router?: Router;\n\n  constructor() {\n    super();\n\n    FIREBASE_STATE.assertInitialized();\n\n    AUTH_STATE.onAuthStateChange(() => {\n      if (this.router == null) {\n        this.router = new Router(document.getElementById('router-outlet'));\n        this.router.setRoutes(ROUTES);\n      }\n    });\n  }\n\n  connectedCallback(): void {\n    super.connectedCallback();\n    this.listenWhileConnected(EventType.SET_TITLE, this.changeTitle.bind(this));\n  }\n\n  protected render() {\n    return html`\n      <inventory-header></inventory-header>\n      <slot name=\"router-outlet\"></slot>\n    `;\n  }\n\n  private changeTitle(ev: SetTitleEvent) {\n    if (ev.title == null) {\n      document.getElementsByTagName('title')[0].innerText = BASE_TITLE;\n    } else {\n      document.getElementsByTagName('title')[0].innerText = `${BASE_TITLE} - ${ev.title}`;\n    }\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    'inventory-app': App;\n  }\n}\n","import {html} from 'lit';\nimport {customElement, property} from 'lit/decorators.js';\n\nimport {assertDefined} from '../../util/asserts';\nimport {BaseElement} from '../base';\nimport {CloseDialogEvent, EventType} from '../events';\n\nimport styles from './styles.scss';\n\nexport const OVERLAY_CLICK_ACTION = 'overlay_click';\nexport const CANCEL_ACTION = 'cancel';\n\n@customElement('inventory-dialog')\nexport class Dialog extends BaseElement {\n  static styles = styles;\n\n  @property({attribute: 'prevent-automatic-close', type: Boolean})\n  preventAutomaticClose = false;\n\n  @property({attribute: false})\n  beforeClose: ((action: string) => boolean) | ((action: string) => Promise<boolean>) = () => true;\n\n  @property({attribute: false})\n  afterClose: ((action: string) => void) | ((action: string) => Promise<void>) = () => {};\n\n  private action = '';\n\n  connectedCallback(): void {\n    super.connectedCallback();\n    this.listenWhileConnected(EventType.CLOSE_DIALOG, this.doClose.bind(this));\n  }\n\n  protected render() {\n    return html`\n      <dialog\n        @click=${this.maybeClose}\n        @cancel=${this.maybeCancel}\n        @close=${this.closed}\n      >\n        <header>\n          <div class=\"title\">\n            <slot name=\"title\"></slot>\n          </div>\n          <div class=\"actions\">\n            <slot name=\"header-actions\">\n              <inventory-dialog-close-button></inventory-dialog-close-button>\n            </slot>\n          </div>\n        </header>\n        <div class=\"body\">\n          <slot name=\"body\"></slot>\n        </div>\n        <footer>\n          <slot name=\"footer\">\n            <div class=\"default-footer\">\n              <inventory-dialog-action-button action=\"done\">\n                <md-text-button>Done</md-text-button>\n              </inventory-dialog-action-button>\n            </div>\n          </slot>\n        </footer>\n      </dialog>\n    `;\n  }\n\n  private get dialog(): HTMLDialogElement {\n    return assertDefined(this.renderRoot.querySelector('dialog'), 'dialog element');\n  }\n\n  showModal() {\n    this.dialog.showModal();\n  }\n\n  showInline() {\n    this.dialog.show();\n  }\n\n  close() {\n    this.dialog.close();\n  }\n\n  private async doClose(ev: CloseDialogEvent) {\n    if (await this.beforeClose(ev.action)) {\n      this.dialog.close();\n      this.action = ev.action;\n    }\n  }\n\n  private async maybeCancel(ev: Event) {\n    if (this.preventAutomaticClose) {\n      ev.preventDefault();\n    }\n    if (await this.beforeClose(CANCEL_ACTION)) {\n      this.action = CANCEL_ACTION;\n    }\n  }\n\n  private async closed() {\n    await this.afterClose(this.action);\n  }\n\n  private async maybeClose(ev: PointerEvent) {\n    if (this.preventAutomaticClose) {\n      return;\n    }\n    const target = ev.target as HTMLElement;\n    if (target == null) {\n      return;\n    }\n    if (target.tagName !== 'DIALOG') {\n      return;\n    }\n    if (\n      ev.offsetX < 0 ||\n      ev.offsetY < 0 ||\n      ev.offsetX > target.clientWidth ||\n      ev.offsetY > target.clientHeight\n    ) {\n      await this.doClose(new CloseDialogEvent(OVERLAY_CLICK_ACTION));\n    }\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    'inventory-dialog': Dialog;\n  }\n}\n","import {html} from 'lit';\nimport {customElement, property} from 'lit/decorators.js';\n\nimport {BaseElement} from '../base';\nimport {CloseDialogEvent} from '../events';\n\n@customElement('inventory-dialog-action-button')\nexport class DialogActionButton extends BaseElement {\n  @property()\n  action!: string;\n\n  connectedCallback(): void {\n    super.connectedCallback();\n\n    this.listenWhileConnected('click', () => {\n      this.dispatchEvent(new CloseDialogEvent(this.action));\n    });\n  }\n\n  protected render() {\n    return html`<slot></slot>`;\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    'inventory-dialog-action-button': DialogActionButton;\n  }\n}\n","import {html} from 'lit';\nimport {customElement} from 'lit/decorators.js';\n\nimport {BaseElement} from '../base';\n\nexport const CLOSE_BUTTON_ACTION = 'close_button';\n\n@customElement('inventory-dialog-close-button')\nexport class DialogCloseButton extends BaseElement {\n  protected render() {\n    return html`\n      <inventory-dialog-action-button action=\"${CLOSE_BUTTON_ACTION}\">\n        <inventory-icon-button button-aria-label=\"Close\"> close </inventory-icon-button>\n      </inventory-dialog-action-button>\n    `;\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    'inventory-dialog-close-button': DialogCloseButton;\n  }\n}\n","import {Router} from '@vaadin/router';\nimport {html} from 'lit';\nimport {customElement} from 'lit/decorators.js';\n\nimport {AUTH_STATE} from '../../firebase/auth_state';\nimport {BaseElement} from '../base';\n\nimport styles from './styles.scss';\n\n@customElement('inventory-header')\nexport class Header extends BaseElement {\n  static styles = styles;\n\n  constructor() {\n    super();\n\n    AUTH_STATE.onAuthStateChange(() => {\n      this.requestUpdate();\n    });\n  }\n\n  protected render() {\n    const title = html`<h1>Five Bit Inventory</h1>`;\n    if (AUTH_STATE.currentUser == null) {\n      return html`\n        ${title}\n        <md-outlined-button @click=\"${this.login}\">Log In</md-outlined-button>\n      `;\n    } else {\n      return html`\n        ${title}\n        <div>Hello, ${AUTH_STATE.currentUser.displayName}!</div>\n        <inventory-user-settings></inventory-user-settings>\n        <md-outlined-button @click=\"${this.logout}\">Log Out</md-outlined-button>\n      `;\n    }\n  }\n\n  private login() {\n    AUTH_STATE.login();\n  }\n\n  private logout() {\n    AUTH_STATE.logout();\n    Router.go('/login');\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    'inventory-header': Header;\n  }\n}\n","import {html, nothing} from 'lit';\nimport {customElement, property} from 'lit/decorators.js';\n\nimport {BaseElement} from '../base';\n\nimport styles from './styles.scss';\n\n@customElement('inventory-icon-button')\nexport class IconButton extends BaseElement {\n  static styles = styles;\n\n  @property({attribute: 'button-aria-label'})\n  buttonAriaLabel = '';\n\n  @property()\n  disabled = false;\n\n  @property()\n  tooltip = '';\n\n  protected render() {\n    return html`\n      <button\n        aria-label=\"${this.buttonAriaLabel || nothing}\"\n        disabled=\"${this.disabled ? 'disabled' : nothing}\"\n        id=\"iconButton\"\n      >\n        <md-icon>\n          <slot></slot>\n        </md-icon>\n      </button>\n      ${this.tooltip === ''\n        ? html``\n        : html`<vaadin-tooltip\n            for=\"iconButton\"\n            text=\"${this.tooltip}\"\n          ></vaadin-tooltip>`}\n    `;\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    'inventory-icon-button': IconButton;\n  }\n}\n","import {Commands, RouterLocation} from '@vaadin/router';\nimport {LitElement, html} from 'lit';\nimport {customElement} from 'lit/decorators.js';\n\nimport {AUTH_STATE} from '../../firebase/auth_state';\nimport {SetTitleEvent} from '../events';\n\nimport styles from './styles.scss';\n\n@customElement('inventory-login-view')\nexport class LoginView extends LitElement {\n  static styles = styles;\n\n  onBeforeEnter(location: RouterLocation, commands: Commands) {\n    if (AUTH_STATE.currentUser != null) {\n      return commands.redirect(new URLSearchParams(location.search).get('next') ?? '/workspaces');\n    }\n  }\n\n  onAfterEnter() {\n    this.dispatchEvent(new SetTitleEvent('Log in'));\n  }\n\n  protected render() {\n    return html`\n      <div class=\"login-message\">\n        <h2>You need to log in</h2>\n        <md-filled-button @click=\"${this.login}\">Log in with Google</md-filled-button>\n      </div>\n    `;\n  }\n\n  private login() {\n    AUTH_STATE.login();\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    'inventory-login-view': LoginView;\n  }\n}\n"],"names":["__rest","s","e","t","p","Object","prototype","hasOwnProperty","call","indexOf","getOwnPropertySymbols","i","length","propertyIsEnumerable","__decorate","decorators","target","key","desc","d","c","arguments","r","getOwnPropertyDescriptor","Reflect","decorate","defineProperty","SuppressedError","n","customElements","define","kind","elements","finisher","descriptor","createProperty","Symbol","placement","originalKey","initializer","this","constructor","o","state","get","renderRoot","querySelector","enumerable","configurable","window","HTMLSlotElement","assignedElements","assignedNodes","filter","nodeType","Node","ELEMENT_NODE","l","slot","selector","matches","ShadowRoot","ShadyCSS","nativeShadow","Document","CSSStyleSheet","WeakMap","o$5","_$cssResult$","Error","cssText","styleSheet","replaceSync","set","toString","reduce","cssRules","trustedTypes","h","emptyScript","reactiveElementPolyfillSupport","toAttribute","Boolean","Array","JSON","stringify","fromAttribute","Number","parse","a","attribute","type","String","converter","reflect","hasChanged","u$1","HTMLElement","super","_$Ei","Map","isUpdatePending","hasUpdated","_$El","u","static","finalize","push","observedAttributes","elementProperties","forEach","_$Ep","_$Ev","noAccessor","getPropertyDescriptor","requestUpdate","getPrototypeOf","properties","getOwnPropertyNames","elementStyles","finalizeStyles","styles","isArray","Set","flat","reverse","unshift","toLowerCase","_$E_","Promise","enableUpdating","_$AL","_$Eg","addController","_$ES","isConnected","hostConnected","removeController","splice","createRenderRoot","shadowRoot","attachShadow","shadowRootOptions","adoptedStyleSheets","map","document","createElement","litNonce","setAttribute","textContent","appendChild","connectedCallback","disconnectedCallback","hostDisconnected","attributeChangedCallback","_$AK","_$EO","removeAttribute","getPropertyOptions","has","_$EC","_$Ej","async","reject","scheduleUpdate","performUpdate","shouldUpdate","willUpdate","hostUpdate","update","_$Ek","_$AE","hostUpdated","firstUpdated","updated","updateComplete","getUpdateComplete","mode","ReactiveElement","reactiveElementVersions","createPolicy","createHTML","Math","random","slice","createComment","f","_","m","RegExp","g","$","y","x","_$litType$","strings","values","w","T","for","A","E","C","createTreeWalker","P","V","v","lastIndex","exec","test","startsWith","N$1","N","parts","el","currentNode","content","firstChild","remove","append","childNodes","nextNode","hasAttributes","getAttributeNames","endsWith","getAttribute","split","index","name","ctor","H","L","z","k","tagName","data","innerHTML","S","_$Co","_$Cl","_$litDirective$","_$AO","_$AT","_$AS","R$1","R","_$AH","_$AN","_$AA","_$AB","_$AM","options","_$Cp","_$AU","parentNode","startNode","endNode","_$AI","_$AR","iterator","insertBefore","nextSibling","createTextNode","_$AC","_$AD","_$AV","creationScope","importNode","Z","_$AP","setConnected","k$1","element","fill","j","H$1","I","z$1","capture","once","passive","removeEventListener","addEventListener","handleEvent","host","Z$1","B","litHtmlPolyfillSupport","litHtmlVersions","D","renderBefore","_$litPart$","renderOptions","_$Do","render","finalized","_$litElement$","globalThis","litElementHydrateSupport","LitElement","litElementPolyfillSupport","litElementVersions","Elevation","html","css","MdElevation","customElement","ATTACHABLE_CONTROLLER","FOR_ATTRIBUTE_OBSERVER","MutationObserver","records","record","AttachableController","htmlFor","control","hasAttribute","getRootNode","currentControl","parentElement","onControlChange","observe","attributeFilter","attach","setCurrentControl","detach","EVENTS","FocusRing","visible","inward","attachableController","bind","event","HANDLED_BY_FOCUS_RING","prev","next","property","MdFocusRing","i$2","_$Ct","_$Ci","keys","join","it","nt","add","classList","delete","EASING","State","Ripple","disabled","hovered","pressed","rippleSize","rippleScale","initialSize","INACTIVE","checkBoundsAfterContextMenu","classes","classMap","changedProps","handlePointerenter","shouldReactToEvent","handlePointerleave","endPressAnimation","handlePointerup","HOLDING","TOUCH_DELAY","WAITING_FOR_CLICK","startPressAnimation","rippleStartEvent","isTouch","inBounds","resolve","setTimeout","handleClick","handlePointercancel","handleContextmenu","determineRippleSize","height","width","getBoundingClientRect","maxDim","max","softEdgeSize","floor","maxRadius","sqrt","getNormalizedPointerEventCoords","pointerEvent","scrollX","scrollY","left","top","documentX","documentY","pageX","pageY","getTranslationCoordinates","positionEvent","endPoint","startPoint","PointerEvent","mdRoot","growAnimation","cancel","translateStart","translateEnd","animate","transform","pseudoElement","duration","easing","animation","pressAnimationPlayState","currentTime","Infinity","isPrimary","pointerId","isPrimaryButton","buttons","bottom","right","pointerType","handlePointerdown","query","MdRipple","_$litStatic$","raw","ARIA_PROPERTIES","ariaPropertyToAttribute","replace","requestUpdateOnAriaChange","ariaProperty","addInitializer","controller","redispatchEvent","bubbles","composed","stopPropagation","copy","construct","dispatched","dispatchEvent","preventDefault","dispatchActivationClick","MouseEvent","isActivationClick","currentTarget","composedPath","squelched","isSquelchingEvents","stopImmediatePropagation","squelchEventsForMicrotask","squelchEvent","formAssociated","trailingIcon","hasIcon","internals","attachInternals","isRedispatchingEvent","handleActivationClick","buttonElement","focus","blur","isDisabled","href","button","literal","ariaLabel","ariaHasPopup","ariaExpanded","staticHtml","getRenderClasses","nothing","renderFocusRing","renderElevation","renderRipple","renderOutline","renderTouchTarget","renderLeadingIcon","renderLabel","renderTrailingIcon","renderIcon","handleSlotChange","form","isSubmit","isReset","prevented","requestSubmit","reset","assignedIcons","Button","delegatesFocus","queryAssignedElements","flatten","FilledButton","MdFilledButton","sharedStyles","sharedElevationStyles","filledStyles","OutlinedButton","MdOutlinedButton","outlinedStyles","TextButton","MdTextButton","textStyles","Checkbox","labels","checked","error","indeterminate","value","prevChecked","prevDisabled","prevIndeterminate","input","changed","shouldAddFormValue","setFormValue","prevNone","isChecked","isIndeterminate","containerClasses","selected","unselected","handleChange","formResetCallback","formStateRestoreCallback","MdCheckbox","Icon","MdIcon","Progress","fourColor","renderIndicator","CircularProgress","renderIndeterminateContainer","renderDeterminateContainer","dashOffset","MdCircularProgress","SingleSelectionController","focused","root","handleFocusIn","updateTabIndices","handleFocusOut","handleKeyDown","isDown","isUp","isLeft","isRight","siblings","getNamedSiblings","forwards","getComputedStyle","direction","hostIndex","nextIndex","sibling","tabIndex","Event","uncheckSiblings","handleCheckedChange","checkedSibling","find","focusable","from","querySelectorAll","_b","CHECKED","maskId","Radio","wasChecked","selectionController","MdRadio","forcedColorsStyles","Field","label","populated","required","supportingText","errorText","count","hasStart","hasEnd","isAnimating","refreshErrorAlert","counterText","supportingOrErrorText","reannounceError","props","animateLabelIfNeeded","wasFocused","wasPopulated","floatingLabel","restingLabel","outline","renderBackground","renderSupportingText","updateSlottedAriaDescribedBy","requestAnimationFrame","start","end","shouldErrorAnnounce","slottedAriaDescribedBy","isFloating","hidden","floating","resting","labelText","labelAnimation","floatingLabelEl","getLabelKeyframes","restingLabelEl","floatingX","floatingY","floatingHeight","restingX","restingY","restingHeight","floatingScrollWidth","scrollWidth","restingScrollWidth","scale","restTransform","round","floatTransform","restingClientWidth","clientWidth","getSurfacePositionClientRect","containerEl","OutlinedField","MdOutlinedField","includes","style","ut","removeProperty","setProperty","stringConverter","TextField","selectionDirection","getInputOrTextarea","selectionEnd","selectionStart","validationMessage","validity","valueAsNumber","getInput","NaN","valueAsDate","willValidate","hasError","nativeError","prefixText","suffixText","hasLeadingIcon","hasTrailingIcon","textDirection","rows","maxLength","min","minLength","pattern","placeholder","readOnly","step","dirty","nativeErrorText","handleFocusin","handleFocusout","checkValidity","valid","checkValidityAndDispatch","reportValidity","canceled","prevMessage","getErrorText","field","select","setCustomValidity","setRangeText","args","setSelectionRange","stepDown","stepDecrement","stepUp","stepIncrement","newValue","oldValue","textarea","renderField","changedProperties","fieldTag","renderInputOrTextarea","handleIconChange","styleMap","live","handleInput","prefix","renderPrefix","suffix","renderSuffix","renderAffix","text","isSuffix","inputOrTextarea","cancelable","leadingIcons","trailingIcons","OutlinedTextField","MdOutlinedTextField","outlinedForcedColorsStyles","Lumo","version","ThemePropertyMixin","superClass","_theme","_set_theme","themeRegistry","classHasThemes","elementClass","registerStyles","themeFor","console","warn","CSSResult","flattenStyles","Vaadin","styleModules","include","moduleId","getAllThemes","getIncludePriority","moduleName","includePriority","getIncludedStyles","theme","includedStyles","concat","includeModuleId","includedTheme","getThemes","defaultModuleName","themes","some","themeForToken","matchesThemeFor","sort","themeA","themeB","ThemableMixin","template","_template","styleEl","addStylesToTemplate","getStylesForThis","themeStyles","parent","inheritedThemes","__themes","is","flatMap","lastIndexOf","addLumoGlobalStyles","id","styleTag","head","insertAdjacentElement","addGlobalThemeStyles","font","JSCompiler_renameProperty","prop","obj","workingURL","resolveDoc","CSS_URL_RX","ABS_URL","resolveUrl","url","baseURI","undefined","URL","pathname","location","implementation","createHTMLDocument","base","anchor","body","resolveCss","pre","post","pathFromUrl","substring","useShadow","ShadyDOM","nativeCss","supportsAdoptingStyleSheets","sheet","rootPath","Polymer","sanitizeDOMValue","setPassiveTouchGestures","strictTemplatePolicy","allowTemplateFromDomModule","legacyOptimizations","legacyWarnings","syncInitialRender","legacyUndefined","orderedComputed","removeNestedTemplates","fastDomIf","suppressTemplateNotifications","legacyNoObservedAttributes","useAdoptedStyleSheetsWithBuiltCSS","dedupeId","dedupingMixin","mixin","mixinApplications","__mixinApplications","mixinDedupeId","baseSet","__mixinSet","extended","mixinSet","create","modules","lcModules","setModule","module","findModule","DomModule","old","namespace","register","assetpath","__assetpath","owner","HTMLImports","importForElement","ownerDocument","inst","MODULE_STYLE_LINK_SELECTOR","INCLUDE_ATTR","SHADY_UNSCOPED_ATTR","importModule","import","styleForImport","importDoc","importCss","stylesFromModules","moduleIds","trim","stylesFromModule","_styles","_stylesFromModuleImports","stylesFromTemplate","e$","item","self","p$","unscoped","_unscopedStyle","_style","wrap","isPath","path","dotIndex","isAncestor","isDescendant","translate","newBase","normalize","info","last","caseMap","DASH_TO_CAMEL","CAMEL_TO_DASH","dashToCamelCase","dash","toUpperCase","camelToDashCase","camel","microtaskCurrHandle","microtaskLastHandle","microtaskCallbacks","microtaskNodeContent","microtaskScheduled","microtaskNode","len","cb","characterData","timeOut","after","delay","run","fn","handle","clearTimeout","microTask","callback","idx","microtask","PropertiesChanged","proto","_createPropertyAccessor","_addPropertyToAttributeMap","__dataHasAccessor","assign","_definePropertyAccessor","__dataAttributes","attr","attributeNameForProperty","__data","_setPendingProperty","_invalidateProperties","__dataEnabled","__dataReady","__dataInvalid","__dataPending","__dataOld","__dataInstanceProps","__dataCounter","__serializing","_initializeProperties","ready","_flushProperties","_initializeInstanceProperties","_setProperty","_getProperty","ext","_shouldPropertyChange","_isPropertyPending","_enableProperties","_shouldPropertiesChange","_propertiesChanged","currentProps","oldProps","_attributeToProperty","_deserializeValue","typeForProperty","_propertyToAttribute","_valueToNodeAttribute","node","str","_serializeValue","nativeProperties","isTrustedType","val","isHTML","isScript","isScriptURL","PropertyAccessors","a$","__dataProto","_initializeProtoProperties","_ensureAttribute","Date","outValue","isNaN","model","saveAccessorValue","_hasAccessor","templateExtensions","placeholderBugDetect","placeholderBug","fixPlaceholder","hasPlaceholderBug","localName","copyAttributeWithTemplateEventPolicy","polymerTemplateEventAttributePolicy","createScript","dest","src","wrapTemplateExtension","replaceChild","attributes","findTemplateNode","nodeInfo","parentInfo","parentIndex","applyIdToMap","applyEventListener","events","_addMethodEventListenerToNode","applyTemplateInfo","parentTemplateInfo","templateInfo","_templateInfo","_parentTemplateInfo","TemplateStamp","outerTemplateInfo","nodeInfoList","nestedTemplate","stripWhiteSpace","_parseTemplateContent","_parseTemplateNode","noted","hasInsertionPoint","_parseTemplateNestedTemplate","_parseTemplateChildNodes","_parseTemplateNodeAttributes","TEXT_NODE","removeChild","childInfo","infoIndex","_parseTemplate","createDocumentFragment","attrs","_parseTemplateNodeAttribute","_stampTemplate","HTMLTemplateElement","dom","__noInsertionPoint","nodes","nodeList","eventName","methodName","context","handler","_methodHost","detail","createNodeEventHandler","_addEventListenerToNode","_removeEventListenerFromNode","NOOP","TYPES","COMPUTE","REFLECT","NOTIFY","PROPAGATE","OBSERVE","READ_ONLY","COMPUTE_INFO","capitalAttributeRegex","ensureOwnEffectMap","cloneArrays","effects","protoFx","instFx","runEffects","hasPaths","extraArgs","ran","fxs","fx","lastRun","pathMatchesTrigger","trigger","runEffectsForProperty","triggerPath","structured","wildcard","runObserverEffect","method","changedProp","dynamicFn","notifyPath","rootProperty","dispatchNotifyEvent","queueProperty","CustomEvent","runNotifyEffect","runReflectEffect","attrName","runComputedEffects","computeEffects","order","ordered","__orderedComputedDeps","curr","counts","total","infoForComputed","computedDeps","dependencyCounts","shift","size","computedByCurr","computedProp","methodInfo","getComputedOrder","queue","enqueueEffectsFor","runComputedEffect","inputProps","insertEffect","mid","cmp","result","runMethodEffect","addBinding","bindings","binding","isCompound","shouldAddListener","negate","listenerEvent","listenerNegate","part","compoundIndex","addEffectForBindingPart","dependencies","evaluator","parseArg","_addTemplatePropertyEffect","runBindingEffect","source","__isPropertyEffectsClient","_setPendingPropertyOrPath","_enqueueClient","_evaluateBinding","storage","__dataCompoundStorage","computeBindingValue","_setUnmanagedPropertyToNode","applyBindingValue","setupCompoundStorage","literals","addNotifyListener","fromProp","toPath","fromPath","handleNotification","createMethodEffect","sig","effectFn","arg","_addPropertyEffect","_marshalArgs","apply","emptyArray","IDENT","ARGUMENT","bindingRegex","OPEN_BRACKET","literalFromParts","parseMethod","expression","match","argList","rawArg","parseArgs","fc","getArgValue","notifySplices","array","splices","splicesData","indexSplices","_overrideLegacyUndefined","notifySplice","addedCount","removed","object","PropertyEffects","propertyEffectsBase","__dataClientsReady","__dataPendingClients","__dataToNotify","__dataLinkedPaths","__dataHasPaths","__dataHost","__dataTemp","__dataClientsInitialized","__computeEffects","__computeInfo","__reflectEffects","__notifyEffects","__propagateEffects","__observeEffects","__readOnly","__templateInfo","PROPERTY_EFFECT_TYPES","_registerHost","hostStack","effect","_removePropertyEffect","_hasPropertyEffect","_hasReadOnlyEffect","_hasNotifyEffect","_hasReflectEffect","_hasComputedEffect","shouldNotify","isPathNotification","links","link","b","computeLinkedPaths","propIsPath","prevProps","client","_flushClients","__enableOrFlushClients","_readyClients","clients","setProperties","setReadOnly","notifyProps","_propagatePropertyChanges","notified","runNotifyEffects","_runEffectsForTemplate","baseRunEffects","propertyEffects","linkPaths","to","unlinkPaths","items","ret","pop","hadLength","deleteCount","propPath","_createReadOnlyProperty","protectedSetter","upper","_createPropertyObserver","_createMethodObserver","_createNotifyingProperty","_createReflectedProperty","_createComputedProperty","pathValue","_bindTemplate","instanceBinding","wasPreBound","__preBoundTemplateInfo","previous","lastChild","previousSibling","hostProps","setupBindings","_removeBoundDom","_parseBindings","origName","nestedTemplateInfo","isDomIf","isDomRepeat","hostProp","customEvent","notifyEvent","colon","signature","dynamicFns","PropertiesMixin","superPropertiesClass","superCtor","ownProperties","output","normalizeProperties","__ownProperties","_properties","__observedAttributes","__finalized","_finalizeClass","createProperties","__properties","builtCSS","ElementMixin","polymerElementBase","createPropertyFromConfig","allProps","computed","reflectToAttribute","notify","observer","processElementStyles","klass","templateStyles","stylesWithImports","linkedStyles","stylesFromModuleImports","firstTemplateChild","firstElementChild","_processStyleText","templateStyleIndex","templateStyle","cloneNode","prepareTemplate","_styleSheet","polymerElementVersion","observers","__ownObservers","createObservers","_prepareTemplate","protoTemplate","importPath","meta","importMeta","_importPath","_finalizeTemplate","__propertyDefaults","propertyDefaults","_canApplyPropertyDefault","__polymerFinalized","styleElement","_attachDom","shadyUpgradeFragment","flushInitial","updateStyles","styleSubtree","policy","LiteralString","assertValidTemplateStringParameters","string","acc","literalValue","htmlValue","TypeError","PolymerElement","directionSubscribers","alignDirs","documentDir","elementDir","getDocumentDir","documentElement","DirMixin","dir","__isRTL","__restoreSubscription","__subscribe","newValueEqlDocDir","newValueEmptied","newDiffValue","__unsubscribe","InputContainer","readonly","invalid","overlay","scheduled","beforeRenderQueue","afterRenderQueue","schedule","callMethod","flushQueue","runQueue","afterNextRender","testUserAgent","regexp","navigator","userAgent","testPlatform","platform","vendor","isFirefox","isIPad","maxTouchPoints","isIOS","isSafari","createEvent","processTemplates","component","templateRendererCallback","counterMap","uncontrolledNodes","markerMap","lockCount","unwrapHost","isElement","logError","applyAttributeToOthers","originalTarget","markerName","controlAttribute","targets","contains","correctedTarget","correctTargets","markerCounter","hiddenNodes","elementsToKeep","elementsToStop","keep","deep","children","alreadyHidden","counterValue","markerValue","clear","hideOthers","AriaModalController","showModal","__showOthers","close","keyboardActive","getDeepActiveElement","activeElement","isKeyboardActive","hasLowerTabOrder","ati","bti","sortElementsByTabIndex","pivot","ceil","mergeSortByTabIndex","isElementFocused","collectFocusableNodes","visibility","display","computedStyle","isElementHiddenDirectly","isElementFocusable","normalizeTabIndex","needsSort","child","FocusRestorationController","saveFocus","focusNode","restoreFocus","instances","FocusTrapController","__trapNode","__onKeyDown","__focusableElements","focusableElements","getFocusableElements","__focusedElementIndex","trapFocus","trapNode","releaseFocus","backward","shiftKey","__focusNextElement","currentIndex","ControllerMixin","__controllers","OverlayFocusMixin","focusTrap","restoreFocusOnClose","restoreFocusNode","__ariaModalController","__focusTrapController","__focusRestorationController","_resetFocus","_shouldRestoreFocus","_saveFocus","_trapFocus","_deepContains","doc","Overlay$1","Overlay","opened","Element","renderer","Function","withBackdrop","modeless","_mouseDownInside","_mouseUpInside","_oldOwner","_oldModel","_oldRenderer","_oldOpened","__attachedInstances","__zIndex","_boundMouseDownListener","_mouseDownListener","_boundMouseUpListener","_mouseUpListener","_boundOutsideClickListener","_outsideClickListener","_boundKeydownListener","_keydownListener","_boundIosResizeListener","_detectIosNavbar","_last","backdrop","innerHeight","landscape","innerWidth","clientHeight","sourceEvent","evt","defaultPrevented","requestContentUpdate","_shouldCloseOnOutsideClick","_event","_openedChanged","wasOpened","_animatedOpening","_addGlobalListeners","_animatedClosing","_removeGlobalListeners","_hiddenChanged","_flushAnimation","_shouldAnimate","getPropertyValue","_enqueueAnimation","listener","_attachOverlay","_enterModalState","_finishOpening","_placeholder","bringToFront","_finishClosing","_detachOverlay","_exitModalState","_modelessChanged","pointerEvents","_previousDocumentPointerEvents","_rendererOrDataChanged","ownerOrModelChanged","rendererChanged","openedChanged","zIndex","frontmost","parseFloat","menuOverlayCore","menuOverlay","DEV_MODE_CODE_REGEXP","FlowClients","Flow","uncommentAndRun","log","runIfDevelopmentMode","developmentMode","maybeGatherAndSendStats","localStorage","getItem","hostname","productionMode","isDevelopmentMode","animationFrame","cancelAnimationFrame","idlePeriod","requestIdleCallback","cancelIdleCallback","queueMicrotask","microtaskFlush","debouncerQueue","Debouncer$1","Debouncer","debouncer","asyncModule","_cancelAsync","setConfig","_asyncModule","_callback","_timer","isActive","flush","enqueueDebouncer","flushDebouncers","didFlush","debouncers","statsJob","registrations","developmentModeCallback","registered","debounce","doctype","newSplice","EDIT_LEAVE","EDIT_UPDATE","EDIT_ADD","EDIT_DELETE","calcSplices","current","currentStart","currentEnd","oldStart","oldEnd","prefixCount","suffixCount","searchLength","equals","sharedPrefix","index1","index2","sharedSuffix","ops","distances","edits","northWest","west","north","spliceOperationsFromEditDistances","rowCount","columnCount","calcEditDistances","oldIndex","currentValue","previousValue","isSlot","deserializeAttributeValue","serializeAttributeValue","addValueToAttribute","removeValueFromAttribute","uniqueId","generateUniqueId","SlotController","EventTarget","slotName","config","multiple","useUniqueId","slotInitializer","defaultId","generateId","initialized","initMultiple","initSingle","observeSlot","getSlotChild","initAddedNode","attachDefaultNode","initNode","getSlotChildren","defaultNode","initCustomNode","_node","teardownNode","__slotObserver","wrapped","_shadyChildrenObserver","_nativeChildrenObserver","_connected","_target","_effectiveNodes","_observer","_scheduled","_boundSchedule","_schedule","connect","_listenSlots","observeChildren","mutations","_processMutations","childList","disconnect","_unlistenSlots","unobserveChildren","_processSlotMutations","mutation","addedNodes","removedNodes","takeRecords","newNodes","getFlattenedNodes","isEmptyTextNode","TooltipController","setTarget","tooltipNode","manual","position","_position","shouldShow","setContext","setManual","setOpened","setPosition","setShouldShow","buttonStyles","passiveTouchGestures","HAS_NATIVE_TA","touchAction","GESTURE_KEY","HANDLED_OBJ","TOUCH_ACTION","MOUSE_EVENTS","MOUSE_WHICH_TO_BUTTONS","MOUSE_HAS_BUTTONS","isMouseEvent","supportsPassive","PASSIVE_TOUCH","opts","IS_TOUCH_ONLY","canBeDisabled","command","fieldset","keygen","optgroup","option","hasLeftMouseButton","ev","which","POINTERSTATE","mouse","mouseIgnoreJob","touch","scrollDecided","trackDocument","stateObj","movefn","upfn","untrackDocument","getComposedPath","noPatch","gestures","recognizers","_findOriginalTarget","_handleNative","gobj","gs","changedTouches","touches","identifier","clientX","clientY","ta","firstTouchAction","shouldPrevent","dx","abs","dy","prevent","_handleTouchAction","handled","skip","flow","addListener","evType","recognizer","deps","dep","gd","_count","setTouchAction","_add","recog","emits","emit","_fire","preventer","evName","_findRecognizerByEvent","downupFire","trackHasMovedEnough","started","trackFire","secondlast","moves","lastmove","ddx","ddy","hover","elementFromPoint","oldNext","deepTargetFind","trackForward","bcr","isSyntheticClick","mousedown","touchstart","touchend","addMove","move","ct","touchmove","click","DisabledMixin","superclass","_disabledChanged","_setAriaDisabled","KeyboardMixin","_onKeyDown","_onKeyUp","_onEnter","_onEscape","ActiveMixin","_activeKeys","_shouldSetActive","_setActive","active","toggleAttribute","FocusMixin","_keyboardActive","_shouldSetFocus","_setFocused","_shouldRemoveFocus","TabindexMixin","tabindex","_lastTabIndex","oldDisabled","_tabindexChanged","ButtonMixin","buttonTemplate","_tooltipController","fieldButton","helper","requiredField","inputFieldShared","PROP_NAMES_VERTICAL","PROP_NAMES_HORIZONTAL","targetResizeObserver","ResizeObserver","entries","entry","__overlay","_updatePosition","PositionMixin","positionTarget","horizontalAlign","verticalAlign","noHorizontalOverlap","noVerticalOverlap","requiredVerticalSpace","__onScroll","__addUpdatePositionEventListeners","__removeUpdatePositionEventListeners","__positionTargetAncestorRootNodes","DOCUMENT_NODE","DOCUMENT_FRAGMENT_NODE","assignedSlot","getAncestorRootNodes","__overlayOpenedChanged","unobserve","__margins","propName","parseInt","__positionSettingsChanged","targetRect","shouldAlignStartVertically","__shouldAlignStartVertically","justifyContent","isRTL","shouldAlignStartHorizontally","__shouldAlignStartHorizontally","flexStart","alignItems","overlayRect","verticalProps","__calculatePositionInOneDimension","horizontalProps","rtl","contentWidth","__oldContentWidth","offsetWidth","viewportWidth","defaultAlignLeft","__shouldAlignStart","contentHeight","__oldContentHeight","offsetHeight","viewportHeight","defaultAlignTop","contentSize","viewportSize","margins","defaultAlignStart","noOverlap","propNames","spaceForStartAlignment","spaceForEndAlignment","spaceForDefaultAlignment","__adjustBottomProperty","cssPropNameToSet","adjustedProp","__oldViewportHeight","__oldViewportWidth","shouldAlignStart","cssPropNameToClear","adjustedValue","diff","memoizedTemplate","DatePickerOverlay","mutablePropertyChange","mutableData","isObject","shouldChange","MutableData","OptionalMutableData","_mutablePropertyChange","newInstance","HTMLTemplateElementExtension","writable","DataTemplate","MutableDataTemplate","templateInstanceBase","TemplateInstanceBase","_configureProperties","__templatizeInstance","__templatizeOwner","__hideTemplateChildren__","_showHideChildren","__templatizeOptions","instanceProps","forwardHostProp","hprop","__hostProps","iprop","parentModel","templateHost","hide","__polymerTextContent__","__polymerReplaced__","__polymerDisplay__","showHideChildren","__parentModel","MutableTemplateInstanceBase","findMethodHost","createTemplatizerClass","templatizerBase","templatize","userNotifyInstanceProp","notifyInstanceProp","createNotifyInstancePropEffect","hasHostProps","addNotifyEffects","addPropagateEffects","methodHost","userForwardHostProp","isTemplate","templatizeTemplateClass","templatizedBase","TemplatizedTemplate","TemplatizedTemplateExtension","createForwardHostPropEffect","declaredProps","warnOnUndeclaredProperties","setPrototypeOf","upgradeTemplate","instProp","baseClass","templatizeInstanceClass","shadyDOM","ScopingShim","elementsHidden","domRepeatBase","DomRepeat","as","indexAs","itemsIndexAs","renderedItemCount","initialCount","targetFramerate","_targetFrameTime","notifyDomChange","reuseChunkedInstances","__instances","__renderDebouncer","__itemsIdxToInstIdx","__chunkCount","__renderStartTime","__itemsArrayChanged","__shouldMeasureChunk","__shouldContinueChunking","__chunkingId","__sortFn","__filterFn","__observePaths","__ctor","__isDetached","__detachInstance","hideElementsGlobally","wrappedParent","__attachInstance","__render","__ensureTemplatized","thisAsTemplate","i$","__getMethodHost","__functionFromPropertyValue","functionOrMethodName","__sortChanged","__debounceRender","__filterChanged","__computeFrameTime","rate","__observeChanged","__handleObservedPaths","paths","__itemsChanged","change","__handleItemPath","isntIdxToItemsIdx","__sortAndFilterItems","limit","__calculateLimit","__updateInstances","__continueChunking","_setRenderedItemCount","filteredItemCount","currentCount","newCount","performance","now","renderTime","ratio","itemsIdxToInstIdx","instIdx","itemIdx","__insertInstance","__detachAndRemoveInstance","wrappedRoot","__stampInstance","beforeRow","beforeNode","itemsPath","dot","itemsIdx","itemSubPath","itemPath","itemForElement","instance","modelForElement","indexForElement","dateEquals","date1","date2","getFullYear","getMonth","getDate","dateAllowed","date","getClosestDate","dates","closestDate","candidate","getTime","extractDateParts","day","month","year","dateAfterXMonths","months","today","setDate","setMonth","parseDate","setFullYear","MonthCalendar","selectedDate","focusedDate","showWeekNumbers","i18n","ignoreTaps","_notTapping","minDate","maxDate","_days","_weeks","focusableDateElement","datePart","monthGrid","_handleTap","_isDisabled","firstDate","lastDate","_getTitle","monthNames","formatTitle","_onMonthGridTouchStart","_dateAdd","delta","_applyFirstDayOfWeek","weekDayNames","firstDayOfWeek","_getWeekDayNames","weekDayNamesShort","weekDay","weekDayShort","__focusedDateChanged","days","_getDate","_showWeekNumbersChanged","_showWeekSeparator","_isToday","_getDays","getDay","startMonth","targetMonth","_getWeeks","_preventDefault","__getDatePart","__isDayDisabled","__isDayFocused","__isDaySelected","__getWeekNumber","dayOfWeek","nearestThursdayDiff","nearestThursday","firstOfJanuary","timeDiff","daysSinceFirstOfJanuary","getISOWeekNumber","__getDayAriaSelected","__getDayAriaDisabled","__getDayAriaLabel","weekdays","__getDayTabindex","InfiniteScroller","bufferSize","_initialScroll","_initialIndex","_buffers","_preventScrollEvent","_mayHaveMomentum","_initialized","bufferOffset","offsetTop","itemHeight","_itemHeightVal","tmpStyleProp","fullHeight","itemHeightPx","_bufferHeight","scroller","scrollTop","translateY","_firstIndex","_reset","_scrollDisabled","forceUpdate","_debouncerUpdateClones","_updateClones","_createElement","_updateElement","_element","_index","_activated","_createPool","_finishInit","_initDone","buffer","_ensureStampedInstance","_itemWrapper","_translateBuffer","up","_scroll","offset","upperThresholdReached","lowerThresholdReached","_debouncerScrollFinish","scrollerRect","_isVisible","container","itemWrapper","tmpInstance","viewPortOnly","bufferIndex","firstIndex","rect","stylesTemplate","DatePickerMonthScroller","DatePickerYearScroller","_yearAfterXYears","DatePickerYear","__updateSelected","MediaQueryController","_boundQueryHandler","_queryHandler","_removeListener","_mediaQuery","matchMedia","_addListener","removeListener","mediaQuery","DatePickerOverlayContent","scrollDuration","_focusedMonthDate","initialPosition","_originDate","_visibleMonthIndex","_desktopMode","_desktopMediaQuery","_translateX","_yearScrollerWidth","_ignoreTaps","_cancelButton","_todayButton","calendars","years","__useSubMonthScrolling","_monthScroller","calendar","scrollers","_track","_clear","_cancel","_toggleYearScroller","btn","__onTodayButtonKeyDown","_onTodayTap","__onCancelButtonKeyDown","__initMonthScroller","__initYearScroller","_closeYearScroller","_toggleAnimateClass","focusCancel","scrollToDate","_calculateWeekScrollOffset","_scrollToPosition","_differenceInMonths","_onMonthScroll","_onMonthScrollTouchStart","__onMonthCalendarKeyDown","_onYearTap","_onYearScroll","_onYearScrollTouchStart","_yearScroller","__updateCancelButton","cancelButton","__updateTodayButton","todayButton","_isTodayAllowed","__updateCalendars","__updateYears","_selectDate","dateToSelect","_desktopModeChanged","desktopMode","_focusedDateChanged","revealDate","scrolledAboveViewport","visibleItems","scrolledBelowViewport","temp","week","_initialPositionChanged","_repositionYearScroller","monthPosition","_repositionMonthScroller","_doIgnoreTaps","_debouncer","_formatDisplayed","formatDate","_close","_scrollToCurrentMonth","yearDelta","targetPosition","_targetPosition","__tryFocusDate","revealResolve","_revealPromise","smoothScroll","timestamp","currentPos","easingFunction","oldPosition","_limit","range","_handleTrack","newTranslateX","_openYearScroller","enable","_isYearScrollerVisible","_translateXChanged","_yearAfterXMonths","__toggleDate","_moveFocusByDays","_moveFocusInsideMonth","_moveFocusByMonths","_onTabKeyDown","section","__focusInput","focusDateElement","__pendingDateFocus","dateElement","keepMonth","dateToFocus","reveal","_focusClosestDate","focusDate","_focusAllowedDate","_dateAllowed","_getDateDiff","todayMidnight","DelegateFocusMixin","autofocus","focusElement","_boundOnBlur","_onBlur","_boundOnFocus","_onFocus","_focusElementChanged","oldElement","_addFocusListeners","__forwardTabIndex","_removeFocusListeners","InputMixin","inputElement","_hasInputValue","_boundOnInput","__onInput","_boundOnChange","_onChange","_hasValue","_inputElementValueProperty","_inputElementValue","_addInputListeners","_removeInputListeners","_forwardInputValue","_inputElementChanged","oldInput","_hasInputValueChanged","hasValue","oldHasValue","_setHasInputValue","_onInput","__userInput","isTrusted","_toggleHasValue","_valueChanged","newVal","oldVal","ClearButtonMixin","clearButtonVisible","clearElement","_onClearButtonMouseDown","_onClearButtonClick","_onClearAction","attributeToTargets","getAttrMap","cleanAriaIDReference","storeAriaIDReference","attributeMap","setAriaIDReference","newId","oldId","fromUser","storedValues","attributeValue","FieldAriaController","__required","__target","__setAriaRequiredAttribute","__setLabelIdToAriaAttribute","__labelId","__labelIdFromUser","__setErrorIdToAriaAttribute","__errorId","__setHelperIdToAriaAttribute","__helperId","setAriaLabel","__label","setRequired","__setAriaLabelToAttribute","setLabelId","labelId","oldLabelId","setErrorId","errorId","setHelperId","helperId","restoreGeneratedAriaIDReference","oldErrorId","oldHelperId","SlotChildObserveController","__updateNodeId","__notifyChange","restoreDefaultNode","updateDefaultNode","observeNode","__nodeObserver","isCurrentNodeMutation","subtree","__hasContent","hasContent","isFirstNode","ErrorController","setErrorMessage","errorMessage","setInvalid","errorNode","HelperController","setHelperText","helperText","helperNode","LabelController","setLabel","labelNode","LabelMixin","_labelController","_labelId","_labelNode","_labelChanged","ValidateMixin","validate","isValid","_setInvalid","_shouldSetInvalid","_invalid","FieldMixin","ariaTarget","accessibleName","accessibleNameRef","_fieldAriaController","_helperController","_errorController","__labelChanged","__helperChanged","_errorNode","_helperNode","hasHelper","_accessibleNameChanged","_accessibleNameRefChanged","hasLabel","_errorMessageChanged","_helperTextChanged","_ariaTargetChanged","_requiredChanged","_invalidChanged","DelegateStateMixin","stateTarget","delegateAttrs","delegateProps","_createDelegateAttrsObserver","_createDelegatePropsObserver","_stateTargetChanged","_ensureAttrsDelegated","_ensurePropsDelegated","_delegateAttribute","_delegateProperty","_delegateAttrsChanged","_delegatePropsChanged","InputConstraintsMixin","constraints","_createConstraintsObserver","_hasValidConstraints","__isValidConstraint","_constraintsChanged","hasConstraints","isLastConstraintRemoved","__previousHasConstraints","constraint","stylesMap","SlotStylesMixin","slotStyles","__applySlotStyles","rootStyles","getRootStyles","insertStyles","InputControlMixin","allowedCharPattern","autoselect","title","_boundOnPaste","_onPaste","_boundOnDrop","_onDrop","_boundOnBeforeInput","_onBeforeInput","__shouldAcceptKey","_markInputPrevented","_preventInputDebouncer","metaKey","ctrlKey","__allowedCharRegExp","pastedText","clipboardData","getData","__allowedTextRegExp","draggedText","dataTransfer","_allowedCharPatternChanged","charPattern","InputController","LabelledInputController","labelController","__preventDuplicateLabelClick","__initLabel","inputClickHandler","OverlayClassMixin","overlayClass","_overlayElement","__updateOverlayClassNames","overlayElement","__initialClasses","__previousClasses","classesToRemove","classesToAdd","VirtualKeyboardController","__setVirtualKeyboardEnabled","inputMode","DatePickerMixin","subclass","_selectedDate","_focusedDate","autoOpenDisabled","_fullscreen","_fullscreenMediaQuery","weekdaysShort","referenceDate","yearStr","substr","adjustedYear","getAdjustedYear","monthName","fullYear","_minDate","_maxDate","_noInput","_ios","_focusOverlayOnOpen","_overlayContent","_boundOnClick","_onClick","_boundOnScroll","_onScroll","_boundOverlayRenderer","_overlayRenderer","_nativeInput","_selectParsedOrFocusedDate","hasFocus","__bringToFront","__dispatchChange","open","_focusAndSelect","__userConfirmedDate","inputValue","inputValid","_getFormattedDate","minMaxValid","inputValidity","_shouldKeepFocusRing","_formatISO","_focus","_isNoInput","fullscreen","ios","pad","num","fmt","yearSign","yearFmt","yearAbs","autocomplete","_applyInputValue","_selectedDateChanged","__keepInputValue","_ignoreFocusedDateChange","newDate","__updateOverlayContent","overlayContent","__updateOverlayContentTheme","__updateOverlayContentFullScreen","_onOverlayEscapePress","_onOverlayOpened","_getInitialPosition","scrollFocusDate","focusables","parsedInitialPosition","parsedDate","_getParsedDate","_isValidDate","_onOverlayClosed","_setSelectionRange","_isClearButton","_onHostClick","keyCode","dateObject","_userInputValueChanged","__computeMinOrMaxDate","dateString","DatePicker","clearButton","_setInputElement","_setFocusElement","_onVaadinOverlayClose","_toggle","comboBoxItem","comboBoxOverlay","ComboBoxItemMixin","_owner","hostDir","__rendererOrItemChanged","__updateLabel","TimePickerItem","IOS","IOS_TOUCH_SCROLLING","ironList","_ratio","_scrollerPaddingTop","_scrollPosition","_physicalSize","_physicalAverage","_physicalAverageCount","_physicalTop","_virtualCount","_estScrollHeight","_scrollHeight","_viewportHeight","_viewportWidth","_physicalItems","_physicalSizes","_firstVisibleIndexVal","_lastVisibleIndexVal","_maxPages","_templateCost","_physicalBottom","_scrollBottom","_virtualEnd","_virtualStart","_physicalCount","_hiddenContentSize","_maxScrollTop","_scrollOffset","_maxVirtualStart","virtualCount","_virtualStartVal","_clamp","_physicalStart","_physicalStartVal","_physicalEnd","_physicalCountVal","_optPhysicalSize","firstVisibleIndex","physicalOffset","_iterateItems","pidx","vidx","_getPhysicalSizeIncrement","lastVisibleIndex","scrollOffset","_scrollHandler","_scrollTop","isScrollingDown","idxAdjustment","_update","reusables","_getReusables","physicalTop","indexes","_debounce","_increasePoolIfNeeded","fromTop","ith","offsetContent","physicalItemHeight","idxs","protectedOffsetContent","virtualStart","virtualEnd","physicalCount","scrollBottom","itemSet","movingUp","_assignModels","_updateMetrics","_positionItems","_updateScrollerSize","_isClientFull","nextIncrease","ts","_isIndexRendered","_focusedVirtualIndex","_getPhysicalIndex","_render","isAttached","updateViewportBoundaries","_itemsChanged","_physicalIndexForKey","_resetScrollPosition","rtn","_computeVidx","_adjustScrollPosition","translate3d","deltaHeight","pos","scrollTarget","estScrollHeight","scrollToIndex","currentTopItem","currentVirtualItem","targetOffsetTop","hiddenContentSize","_resetAverage","_resizeHandler","toggleScrollListener","_debouncers","OFFSET_ADJUST_MIN_THRESHOLD","IronListAdapter","createElements","updateElement","scrollContainer","elementsContainer","reorderElements","_vidxOffset","__placeholderHeight","__elementHeightQueue","timeouts","SCROLL_REORDER","IGNORE_WHEEL","FIX_INVALID_ITEM_POSITIONING","__resizeObserver","overflow","_scrollLineHeight","_getScrollLineHeight","__onWheel","__mouseDown","__pendingReorder","__reorderElements","adjustedFirstVisibleIndex","adjustedLastVisibleIndex","visibleElementCount","__getVisibleElements","targetVirtualIndex","__skipNextVirtualIndexAdjust","grid","__getIndexScrollOffset","__fixInvalidItemPositioningDebouncer","__scrollReorderDebouncer","__debouncerWheelAnimationFrame","startIndex","endIndex","updatedElements","__virtualIndex","__updateElement","__afterElementsUpdated","newPhysicalSize","oldPhysicalSize","prevAvgCount","prevPhysicalAvg","__getBorderBoxHeight","boxSizing","paddingBottom","paddingTop","borderBottomWidth","borderTopWidth","forceSameIndexUpdates","__preventElementUpdates","__lastUpdatedIndex","elementHeight","__placeholderClearDebouncer","filteredHeights","__size","_isRTL","_scrollPageHeight","_updateGridMetrics","physicalItems","fragment","__clientFull","_x","_z","_adjustVirtualIndexOffset","__previousScrollTop","__fixInvalidItemPositioning","physicalTopBelowTop","physicalBottomAboveBottom","firstIndexVisible","lastIndexVisible","originalRatio","_hasScrolledAncestor","deltaX","deltaY","deltaMode","WheelEvent","DOM_DELTA_LINE","DOM_DELTA_PAGE","_deltaYAcc","_wheelAnimationFrame","momentum","_canScroll","scrollLeft","_hasResidualMomentum","_ignoreNewWheel","_debouncerIgnoreNewWheel","_previousMomentum","scrollHeight","missingItemCount","fontSize","adjustedVirtualStart","visibleElements","targetElement","targetPhysicalIndex","oldOffset","threshold","maxShift","maxOffset","Virtualizer","__adapter","ComboBoxPlaceholder","ComboBoxScrollerMixin","focusedIndex","loading","selectedItem","itemIdPath","getItemLabel","__boundOnItemClick","__onItemClick","_viewportTotalPaddingBottom","_cachedViewportTotalPaddingBottom","itemsStyle","sum","__hostTagName","__patchWheelOverScrolling","__virtualizer","__createElements","scrollIntoView","visibleItemsCount","_visibleItemsCount","targetIndex","lastPhysicalItem","lastPhysicalItemRect","scrollTopAdjust","_isItemSelected","__loadingChanged","__openedChanged","__selectedItemChanged","__focusedIndexChanged","__rendererChanged","oldRenderer","__requestItemByIndex","scrolledToTop","scrolledToBottom","currentScrollerPos","_oldScrollerPosition","TimePickerScroller","ComboBoxOverlayMixin","comboBox","_comboBox","eventPath","_setOverlayWidth","propPrefix","customWidth","TimePickerOverlay","isValidValue","findItemIndex","findIndex","ComboBoxMixin","allowCustomValue","filteredItems","_lastCommittedValue","_focusedIndex","itemLabelPath","itemValuePath","_toggleElement","_closeOnBlurIsPrevented","_scroller","_overlayOpened","_boundOnFocusout","_onFocusout","_boundOverlaySelectedItemChanged","_overlaySelectedItemChanged","_boundOnClearButtonMouseDown","__onClearButtonMouseDown","_boundOnOverlayTouchAction","_onOverlayTouchAction","_boundOnTouchend","_onTouchend","_tagNamePrefix","autocapitalize","_revertInputValueToValue","_initOverlay","_initScroller","bringToFrontListener","_getItemElements","_filterChanged","scrollerTag","_getItemLabel","_updateScroller","maxHeight","_openedOrItemsChanged","_overlayOpenedChanged","_onOpened","_focusedIndexChanged","_updateActiveDescendant","_isInputFocused","_openedWithFocusRing","_onClosed","_onToggleButtonClick","_onArrowDown","_onArrowUp","_getItemValue","_prefillFocusedItemLabel","focusedItem","_markAllSelectionRange","_clearSelectionRange","_closeOrCommit","_commitValue","hasInvalidOption","_revertInputValue","_toggleElementChanged","toggleElement","_detectAndDispatchChange","itemMatchingInputValue","__getItemIndexByLabel","customValue","_lastCustomValue","_itemLabelPathChanged","_scrollIntoView","_filterItems","_filteredItemsChanged","_selectedItemChanged","_selectItemForValue","oldItems","_ensureItemsOrDataProvider","oldFilteredItems","valueIndex","__getItemIndexByValue","focusedItemIndex","arr","previouslySelectedItem","dataProvider","relatedTarget","TimePickerComboBox","PatternMixin","MIN_ALLOWED_TIME","MAX_ALLOWED_TIME","TimePicker","__dropdownItems","formatTime","time","timeString","hours","minutes","seconds","milliseconds","parseTime","MATCH_MINUTES","_comboBoxValue","_inputContainer","timePicker","_timeAllowed","__validDayDivisor","stepResolution","__onArrowPressWithStep","objWithStep","__addStep","__getMsec","__memoValue","__validateTime","__getSec","msec","precision","stepMsec","diffToNext","hh","mm","ss","__updateDropdownItems","i8n","minTimeObj","__parseISO","minSec","maxTimeObj","maxSec","__generateDropdownList","__oldStep","parsedObj","__updateValue","generatedList","timeObj","formatted","__formatISO","__keepInvalidInput","__updateInputValue","__comboBoxValueChanged","__onComboBoxChange","__onComboBoxHasInputValueChanged","timeObject","stepSegment","__getStepSegment","parsedMin","parsedMax","TooltipOverlay","DEFAULT_DELAY","defaultFocusDelay","defaultHoverDelay","defaultHideDelay","closing","warmedUp","warmUpTimeout","cooldownTimeout","TooltipStateController","openedProp","focusDelay","tooltip","hoverDelay","hideDelay","immediate","isHover","isFocus","__closeTimeout","__showTooltip","__warmupTooltip","__scheduleClose","__abortClose","_setOpened","__abortWarmUp","__abortCooldown","__scheduleCooldown","_isOpened","__flushClosingTooltips","_stateController","__scheduleWarmUp","Tooltip","_context","generator","_autoOpened","__effectivePosition","__isTargetHidden","_isConnected","_uniqueId","_renderer","__tooltipRenderer","__onFocusin","__onFocusout","__onMouseDown","__onMouseEnter","__onMouseLeave","__onOverlayOpen","__targetVisibilityObserver","IntersectionObserver","__onTargetVisibilityChange","isIntersecting","__computeHorizontalAlign","__computeNoHorizontalOverlap","__computeNoVerticalOverlap","__computeVerticalAlign","__computeOpened","autoOpened","connected","__computePosition","defaultPosition","__autoOpenedChanged","oldOpened","__forChanged","forId","__setTargetByIdDebouncer","__setTargetById","targetId","getElementById","__targetChanged","oldTarget","__isShouldShow","__focusInside","__hoverInside","__handleMouseLeave","__onOverlayMouseLeave","isVisible","oldHidden","__textChanged","oldText","__generatorChanged","__oldTextGenerator","__oldContext","clamp","number","digits","pow","hexToRgba","hex","hsvaToHslString","hsva","hsvaToHsla","hsvaToRgba","format","rgbaToHex","alphaHex","rgbaToHsva","equalColorObjects","first","second","cache","tpl","fire","hasTouched","pointerMove","pointer","getMove","pageXOffset","pageYOffset","Slider","aria","xy","dragging","toggleEvent","keyMove","Hue","color","Saturation","$isSame","$color","$hsva","$update","$parts","$css","$sliders","ColorPicker","newColor","newHsva","colorModel","toHsva","slider","defaultColor","_attr","_oldVal","fromAttr","oldHsva","fromHsva","equal","HexBase","_$breadcrumbTypes_8","_$reduce_17","accum","_$filter_12","_$includes_13","_$isArray_14","_hasDontEnumBug","_dontEnums","_$keys_15","_$intRange_24","_$listOfFunctions_25","_$stringWithLength_26","_$config_5","defaultErrorTypes","unhandledExceptions","unhandledRejections","schema","apiKey","defaultValue","message","appVersion","appType","autoDetectErrors","enabledErrorTypes","allowPartialObject","providedKeys","defaultKeys","onError","onSession","onBreadcrumb","endpoints","sessions","autoTrackSessions","enabledReleaseStages","releaseStage","maxBreadcrumbs","enabledBreadcrumbTypes","maybeType","user","metadata","logger","redactedKeys","plugins","load","featureFlags","feature","_$assign_11","_$map_16","_extends","_$config_1","debug","getPrefixedConsole","consoleLog","consoleMethod","_$Breadcrumb_3","Breadcrumb","toJSON","metaData","_$stackframe_34","factory","StackFrame","_isNumber","isFinite","_capitalize","charAt","_getter","booleanProps","numericProps","stringProps","arrayProps","getArgs","setArgs","getEvalOrigin","evalOrigin","setEvalOrigin","getFunctionName","getFileName","getLineNumber","getColumnNumber","_$errorStackParser_31","ErrorStackParser","FIREFOX_SAFARI_STACK_REGEXP","CHROME_IE_STACK_REGEXP","SAFARI_NATIVE_CODE_REGEXP","stacktrace","parseOpera","stack","parseV8OrIE","parseFFOrSafari","extractLocation","urlLike","line","sanitizedLine","tokens","locationParts","functionName","fileName","lineNumber","columnNumber","functionNameRegex","parseOpera9","parseOpera11","parseOpera10","lineRE","lines","argsRaw","functionCall","_$errorStackParser_10","_$safeJsonStringify_30","replacer","space","redactedPaths","prepareObjForSerialization","MAX_DEPTH","MAX_EDGES","MIN_PRESERVED_DEPTH","REPLACEMENT_NODE","isError","throwsMessage","err","haystack","needle","isDescendent","shouldRedact","patterns","__isArray_30","safelyGetProp","seen","edges","visit","edgesExceeded","fResult","eResult","aResult","existingFeatures","existingFeatureKeys","variant","existingIndex","merge","newFeatures","toEventApi","_ref","flag","featureFlag","features","featuresIndex","_$featureFlagDelegate_18","_$hasStack_19","__isError_32","_$iserror_20","__add_22","keyOrObj","maybeVal","_updates","updates","__clear_22","_$metadataDelegate_22","_$stackGenerator_33","StackGenerator","backtrace","maxStackSize","callee","$1","caller","errorClass","handledState","originalError","defaultHandledState","groupingHash","_handledState","severity","unhandled","app","device","request","breadcrumbs","threads","_metadata","_features","_featuresIndex","_user","_session","errors","createBugsnagError","__type","_proto","addMetadata","getMetadata","clearMetadata","addFeatureFlag","addFeatureFlags","getFeatureFlags","clearFeatureFlag","clearFeatureFlags","getUser","setUser","email","payloadVersion","exceptions","er","severityReason","session","formatStackframe","frame","file","normaliseFunctionName","code","inProject","ensureString","getCauseStack","cause","getStacktrace","errorFramesToSkip","backtraceFramesToSkip","maybeError","tolerateNonErrors","_normaliseError","normaliseError","internalFrames","makeSerialisable","_event$errors","causes","normalisedCauses","createAndLogInputError","reason","verb","hasNecessaryFields","_$Event_6","_$asyncEvery_7","_$callbackRunner_9","callbacks","onCallbackError","runMaybeAsyncCallback","then","_$syncCallbackRunner_23","callbackArg","callbackType","ignore","cbs","_$pad_29","env","globalCount","mimeTypesLength","mimeTypes","clientId","_$fingerprint_28","blockSize","discreteValues","randomBlock","safeCounter","cuid","fingerprint","_$cuid_27","Session","startedAt","_handled","_unhandled","_$Session_35","__add_4","__clear_4","__merge_4","noop","Client","configuration","internalPlugins","notifier","_this","_notifier","_config","_schema","_delivery","sendSession","sendEvent","_logger","_plugins","_breadcrumbs","_cbs","sp","_configure","pl","_loadPlugin","_depth","getContext","plugin","configSchema","_reduce","generateConfigErrorMessage","getPlugin","_setDelivery","startSession","_sessionDelegate","addOnError","front","removeOnError","_addOnSessionPayload","addOnSession","removeOnSession","addOnBreadcrumb","removeOnBreadcrumb","pauseSession","resumeSession","leaveBreadcrumb","crumb","_isBreadcrumbTypeEnabled","types","postReportCallback","_notify","_this2","originalSeverity","shouldSend","unhandledOverridden","rawInput","_$Client_4","_$jsonPayload_21","EVENT_REDACTION_PATHS","payload","_$delivery_36","win","getApiUrl","req","XDomainRequest","onload","onerror","toFixed","send","endpoint","isoDate","matchPageProtocol","protocol","encodeURIComponent","_matchPageProtocol","pageProtocol","_$delivery_37","XMLHttpRequest","onreadystatechange","readyState","DONE","status","setRequestHeader","toISOString","appStart","_$app_38","_$context_39","_$pad_43","__env_42","__globalCount_42","__prop_42","__mimeTypesLength_42","__clientId_42","_$fingerprint_42","__c_41","__blockSize_41","__base_41","__discreteValues_41","__randomBlock_41","__safeCounter_41","__cuid_41","_$cuid_41","BUGSNAG_ANONYMOUS_ID_KEY","getDeviceId","setItem","_$device_40","nav","locale","browserLanguage","systemLanguage","userLanguage","language","screen","orientation","generateAnonymousId","collectUserIp","setDefaultUserId","eventOrSession","_$request_44","_$session_45","sessionDelegate","sessionClient","_pausedSession","_$clientIp_46","clientIp","_$consoleBreadcrumbs_47","CONSOLE_LOG_METHODS","original","_len","_key","stringified","_restore","MAX_LINE_LENGTH","MAX_SCRIPT_LENGTH","_$inlineScriptContent_48","trackInlineScripts","originalLocation","DOMContentLoaded","attachEvent","getHtml","outerHTML","_lastScript","updateLastScript","script","getCurrentScript","currentScript","scripts","getElementsByTagName","addSurroundingCode","htmlLines","zeroBasedLine","_setTimeout","__proxy","__traceOriginalScript","eventTargetCallbackAccessor","callbackAccessor","alsoCallOriginal","cba","__trace__","replacement","isEventHandlerObj","_$interactionBreadcrumbs_49","targetText","targetSelector","getNodeText","getNodeSelector","trimStart","trimEnd","innerText","className","_$navigationBreadcrumbs_50","drop","oldURL","relativeLocation","newURL","getCurrentState","history","replaceState","wrapHistoryFn","pushState","search","hash","stateChangeToMetadata","currentPath","prevState","orig","resetEventCount","BREADCRUMB_TYPE","_$networkBreadcrumbs_51","_ignoredUrls","ignoredUrls","monkeyPatchXMLHttpRequest","monkeyPatchFetch","handleFetchSuccess","response","handleFetchError","nativeOpen","requestSetupKey","handleXHRError","handleXHRLoad","fetch","polyfill","oldFetch","_arguments","urlOrRequest","_$throttle_52","maxEvents","_$stripQueryString_53","strip","allFrames","_strip","_$onerror_54","prevOnError","messageOrEvent","lineNo","charNo","decorateStack","extraParameters","culprit","isActualNumber","errorCharacter","_$unhandledRejection_55","isBluebird","fixBluebirdStacktrace","_event$addMetadata","onunhandledrejection","promise","_$notifier_2","__schema_2","Bugsnag","_client","createClient","bugsnag","isStarted","stringToByteArray$1","out","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","webSafe","init_","byteToCharMap","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","encodeString","btoa","decodeString","bytes","c1","fromCharCode","c2","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","byte4","DecodeBase64StringError","base64urlEncodeWithoutPadding","utf8Bytes","base64Encode","base64Decode","getDefaultsFromGlobal","global","getGlobal","__FIREBASE_DEFAULTS__","getDefaults","process","defaultsJsonString","getDefaultsFromEnvVariable","cookie","decoded","getDefaultsFromCookie","getDefaultEmulatorHost","productName","_a","emulatorHosts","getDefaultEmulatorHostnameAndPort","separatorIndex","port","getDefaultAppConfig","getExperimentalSetting","Deferred","wrapCallback","catch","createMockUserToken","token","projectId","uid","project","iat","sub","user_id","iss","aud","exp","auth_time","firebase","sign_in_provider","identities","alg","getUA","FirebaseError","customData","captureStackTrace","ErrorFactory","service","serviceName","fullCode","PATTERN","replaceTemplate","fullMessage","deepEqual","aKeys","bKeys","aProp","bProp","thing","querystring","querystringParams","params","arrayVal","ObserverProxy","executor","onNoObservers","unsubscribes","observerCount","task","forEachObserver","complete","subscribe","nextOrObserver","methods","implementsAnyMethods","unsub","unsubscribeOne","finalError","sendOne","getModularInstance","_delegate","NotificationContainer","_boundVaadinOverlayClose","NotificationCard","Notification$1","Notification","contents","isTemplateResult","_createAndShowNotification","notification","_container","_card","_rendererChanged","card","_didAnimateNotificationAppend","_animatedAppendNotificationCard","_closeNotificationCard","_appendNotificationCard","_removeNotificationCard","_durationTimeoutId","_animatedRemoveNotificationCard","_positionChanged","_durationChanged","toArray","objectOrArray","msg","MODULE","NOMODULE","bundleKeys","ensureBundle","ensureRoute","route","isString","bundle","stringKeys","isFunction","action","redirect","overriddenProp","ensureRoutes","routes","loadScript","__dynamicImportLoaded","fireRouterEvent","getNotFoundError","notFoundResult","vaadinRouterGlobalClickHandler","altKey","nodeName","origin","getAnchorOrigin","scrollTo","CLICK","activate","inactivate","vaadinRouterGlobalPopstateHandler","PopStateEvent","inType","initEvent","POPSTATE","pathToRegexp_1","pathToRegexp$1","parse_1","compile_1","tokensToFunction","tokensToFunction_1","tokensToRegExp_1","tokensToRegExp","DEFAULT_DELIMITER","DEFAULT_DELIMITERS","PATH_REGEXP","res","defaultDelimiter","delimiter","delimiters","pathEscaped","escaped","group","modifier","partial","repeat","optional","escapeGroup","escapeString","encode","segment","flags","sensitive","strict","isEndDelimited","groups","regexpToRegexp","arrayToRegexp","stringToRegexp","compile","cache$1","decodeParam","decodeURIComponent","matchRoute","ignoreLeadingSlash","parentKeys","parentParams","childMatches","childIndex","routepath","routeToSkip","done","__children","exact","cacheKey","matchPath","childRoute","matchedLength","childMatch","resolveRoute","Resolver","baseUrl","errorHandler","resolver","__synthetic","getRoutes","setRoutes","newRoutes","addRoutes","removeRoutes","pathnameOrContext","__normalizePathname","nextMatches","currentContext","resume","prevResult","parentRoute","isChildRoute","chain","updateChainForRoute","resolution","routePath","generateErrorMessage","DOMException","__effectiveBaseUrl","__createUrl","normalizedUrl","pathToRegexp","cacheRoutes","routesByName","getRouteByName","routeName","getRoutePath","generateUrls","router","fullPath","rt","stringifyQueryParams","queryParams","triggers","setNavigationTriggers","newTriggers","elem","willAnimate","waitForAnimation","isResultNotEmpty","createLocation","redirectFrom","getUrl","userParams","getPathnameForRouter","Router","getMatchedPath","createRedirect","runCallbackIfPossible","thisArg","amend","amendmentFunction","amendmentResult","removeDomNodes","outlet","baseElement","baseHref","__resolveRoute","NavigationTrigger","setTriggers","__lastStartedRenderId","__navigationEventHandler","__onNavigationEvent","setOutlet","__createdByRouter","__addedByRouter","copyContextWithoutNext","newChildren","childRoutes","processNewChildren","commands","__isLatestRender","race","__ensureOutlet","__outlet","getOutlet","skipRender","__previousContext","__urlForName","shouldUpdateHistory","renderId","__renderId","__fullyResolveChain","previousContext","__updateBrowserHistory","__skipAttach","__copyUnchangedElements","__addAppearingContent","animationDone","__animateIfNeeded","__runOnAfterEnterCallbacks","__runOnAfterLeaveCallbacks","__removeDisappearingContent","topOfTheChainContextBeforeRedirects","contextBeforeRedirects","__findComponentContextAfterAllRedirects","contextAfterRedirects","topOfTheChainContextAfterRedirects","isFound","findNextContextIfAny","nextContext","__amendWithOnBeforeCallbacks","renderElement","__redirect","__redirectCount","stringType","logValue","contextWithFullChain","__runOnBeforeCallbacks","amendedContext","newContext","previousChain","newChain","__divergedChainIndex","__isReusableElement","__runOnBeforeLeaveCallbacks","__runOnBeforeEnterCallbacks","chainElement","afterLeaveFunction","beforeEnterFunction","otherElement","redirectData","counter","urlForPath","changeState","deepestCommonParent","unchangedElement","__removeAppearingContent","__appearingContent","__disappearingContent","elementToAdd","targetContext","currentComponent","onAfterLeave","onAfterEnter","promises","leave","enter","all","unsubscribe","urlForName","Component","instanceFactory","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","setMultipleInstances","setServiceProps","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","Provider","instancesDeferred","instancesOptions","onInitCallbacks","normalizedIdentifier","normalizeInstanceIdentifier","deferred","isInitialized","shouldAutoInitialize","getOrInitializeService","instanceIdentifier","getImmediate","getComponent","setComponent","isComponentEager","instanceDeferred","clearInstance","services","INTERNAL","_delete","isComponentSet","getOptions","initialize","onInit","existingCallbacks","existingInstance","invokeOnInitCallbacks","ComponentContainer","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","LogLevel","levelStringToEnum","DEBUG","verbose","VERBOSE","INFO","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","logLevel","Logger","_logLevel","_logHandler","_userLogHandler","setLogLevel","logHandler","userLogHandler","instanceOfAny","constructors","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","receiver","IDBTransaction","objectStoreNames","objectStore","wrapFunction","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","unwrap","storeNames","tx","transformCachableValue","unlisten","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","Proxy","IDBRequest","success","promisifyRequest","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","storeName","store","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","isVersionServiceProvider","library","logString","name$o","version$1","PLATFORM_LOG_STRING","_apps","_components","_addComponent","_registerComponent","componentName","_getProvider","heartbeatController","triggerHeartbeat","ERROR_FACTORY","FirebaseAppImpl","_isDeleted","_options","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","checkDestroyed","isDeleted","appName","SDK_VERSION","initializeApp","rawConfig","existingApp","newApp","getApp","registerVersion","libraryKeyOrName","libraryMismatch","versionMismatch","warning","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","blocked","upgrade","blocking","terminated","indexedDB","openPromise","oldVersion","newVersion","db","openDB","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","put","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","read","agent","getUTCDateString","lastSentHeartbeatDate","heartbeats","singleDateHeartbeat","hbTimestamp","valueOf","overwrite","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","heartbeatEntry","hb","countBytes","extractHeartbeatsForHeader","headerString","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","isIndexedDBAvailable","preExist","DB_CHECK_NAME","onsuccess","deleteDatabase","onupgradeneeded","idbHeartbeatObject","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","_prodErrorMap","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logError","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","fullParams","_errorFactory","_assert","assertion","debugFail","failure","debugAssert","_getCurrentUrl","_getCurrentScheme","_isOnline","onLine","runtime","chrome","browser","isBrowserExtension","Delay","shortDelay","longDelay","isMobile","_emulatorUrl","emulator","FetchProvider","fetchImpl","headersImpl","responseImpl","Headers","Response","SERVER_ERROR_MAP","CREDENTIAL_MISMATCH","MISSING_CUSTOM_TOKEN","INVALID_IDENTIFIER","MISSING_CONTINUE_URI","INVALID_PASSWORD","MISSING_PASSWORD","EMAIL_EXISTS","PASSWORD_LOGIN_DISABLED","INVALID_IDP_RESPONSE","INVALID_PENDING_TOKEN","FEDERATED_USER_ID_ALREADY_LINKED","MISSING_REQ_TYPE","EMAIL_NOT_FOUND","RESET_PASSWORD_EXCEED_LIMIT","EXPIRED_OOB_CODE","INVALID_OOB_CODE","MISSING_OOB_CODE","CREDENTIAL_TOO_OLD_LOGIN_AGAIN","INVALID_ID_TOKEN","TOKEN_EXPIRED","USER_NOT_FOUND","TOO_MANY_ATTEMPTS_TRY_LATER","INVALID_CODE","INVALID_SESSION_INFO","INVALID_TEMPORARY_PROOF","MISSING_SESSION_INFO","SESSION_EXPIRED","MISSING_ANDROID_PACKAGE_NAME","UNAUTHORIZED_DOMAIN","INVALID_OAUTH_CLIENT_ID","ADMIN_ONLY_OPERATION","INVALID_MFA_PENDING_CREDENTIAL","MFA_ENROLLMENT_NOT_FOUND","MISSING_MFA_ENROLLMENT_ID","MISSING_MFA_PENDING_CREDENTIAL","SECOND_FACTOR_EXISTS","SECOND_FACTOR_LIMIT_EXCEEDED","BLOCKING_FUNCTION_ERROR_RESPONSE","RECAPTCHA_NOT_ENABLED","MISSING_RECAPTCHA_TOKEN","INVALID_RECAPTCHA_TOKEN","INVALID_RECAPTCHA_ACTION","MISSING_CLIENT_TYPE","MISSING_RECAPTCHA_VERSION","INVALID_RECAPTCHA_VERSION","INVALID_REQ_TYPE","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","tenantId","_performApiRequest","customErrorMap","_performFetchWithErrorHandling","headers","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","clearNetworkTimeout","json","_makeTaggedError","ok","serverErrorCode","serverErrorMessage","authError","apiScheme","timer","errorParams","phoneNumber","_tokenResponse","utcTimestampToDateString","utcTimestamp","toUTCString","secondsStringToMilliseconds","_parseToken","algorithm","_logoutIfInvalidated","bypassAuthState","isUserInvalidated","currentUser","signOut","ProactiveRefresh","isRunning","timerId","errorBackoff","_start","_stop","getInterval","wasError","interval","stsTokenManager","expirationTime","iteration","getIdToken","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","creationTime","_copy","_reloadWithoutSaving","idToken","getAccountInfo","users","coreAccount","_notifyReloadListener","newProviderData","providerUserInfo","providerId","rawId","displayName","photoURL","photoUrl","providerData","newData","deduped","mergeProviderData","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","localId","emailVerified","StsTokenManager","refreshToken","accessToken","isExpired","updateFromServerResponse","expiresIn","parsedToken","_tokenExpiresIn","updateTokensAndExpiration","forceRefresh","refresh","clearRefreshToken","oldToken","grant_type","refresh_token","tokenApiHost","access_token","expires_in","requestStsToken","expiresInSec","manager","_assign","_clone","_performRefresh","assertStringOrUndefined","UserImpl","opt","proactiveRefresh","reloadUserInfo","reloadListener","getToken","_persistUserIfCurrent","_notifyListenersIfCurrent","getIdTokenResult","userInternal","claims","signInProvider","authTime","issuedAtTime","signInSecondFactor","reload","userInfo","newUser","_onReload","_startProactiveRefresh","_stopProactiveRefresh","tokensRefreshed","deleteAccount","_redirectEventId","_c","_d","_e","_f","_g","_h","plainObjectTokenManager","fromJSON","idTokenResponse","instanceCache","_getInstance","cls","InMemoryPersistence","_listener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","setCurrentUser","_set","blob","_get","_fromJSON","removeCurrentUser","_remove","savePersistenceForRedirect","newPersistence","getCurrentUser","persistenceHierarchy","availablePersistences","_isAvailable","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","ua","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","re","_isIOS","_isIE10","isIE","documentMode","_isMobileBrowser","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","getRecaptchaConfig","isEnterprise","grecaptcha","enterprise","RecaptchaConfig","siteKey","emailPasswordEnabled","recaptchaKey","recaptchaEnforcementState","enforcementState","_loadJS","charset","getScriptParentElement","RecaptchaEnterpriseVerifier","authExtern","_castAuth","retrieveRecaptchaToken","execute","_agentRecaptchaConfig","_tenantRecaptchaConfigs","clientType","retrieveSiteKey","AuthMiddlewareQueue","pushCallback","onAbort","wrappedCallback","nextUser","onAbortStack","beforeStateCallback","originalMessage","AuthImpl","heartbeatServiceProvider","appCheckServiceProvider","emulatorConfig","operations","authStateSubscription","Subscription","idTokenSubscription","beforeStateQueue","redirectUser","isProactiveRefreshEnabled","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","lastNotifiedUid","settings","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","_initializeWithPersistence","popupRedirectResolver","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","authDomain","getOrInitRedirectPersistenceManager","redirectUserEventId","storedUserEventId","tryRedirectSignIn","directlySetCurrentUser","runMiddleware","_overrideRedirectResult","reloadAndSetCurrentUserOrClear","redirectResolver","_completeRedirectFn","_setRedirectUser","useDeviceLanguage","navigatorLanguage","languages","_getUserLanguage","userExtern","skipBeforeStateCallbacks","notifyAuthListeners","redirectPersistenceManager","setPersistence","verify","_getRecaptchaConfig","_getPersistence","_updateErrorMap","onAuthStateChanged","completed","registerStateListener","beforeAuthStateChanged","onIdTokenChanged","authStateReady","redirectManager","_redirectPersistence","currentUid","subscription","addObserver","_logFramework","framework","_getFrameworks","heartbeatsHeader","getHeartbeatsHeader","appCheckToken","_getAppCheckToken","appCheckTokenResult","_logWarn","proxy","createSubscribe","connectAuthEmulator","authInternal","disableWarnings","extractProtocol","authority","hostAndPort","bracketedIPv6","parsePort","extractHostAndPort","portStr","freeze","attachBanner","sty","backgroundColor","border","margin","textAlign","emitEmulatorWarning","protocolEnd","AuthCredential","signInMethod","_getIdTokenResponse","_auth","_linkToIdToken","_idToken","_getReauthenticationResolver","signInWithIdp","serverResponse","_serverResponse","_performSignInRequest","OAuthCredential","pendingToken","cred","nonce","oauthToken","oauthTokenSecret","secret","buildRequest","autoCreate","requestUri","returnSecureToken","postBody","FederatedAuthProvider","defaultLanguageCode","customParameters","setDefaultLanguage","setCustomParameters","customOAuthParameters","getCustomParameters","BaseOAuthProvider","scopes","addScope","scope","getScopes","FacebookAuthProvider","_fromParams","PROVIDER_ID","FACEBOOK_SIGN_IN_METHOD","userCredential","credentialFromTaggedObject","tokenResponse","oauthAccessToken","credential","GoogleAuthProvider","GOOGLE_SIGN_IN_METHOD","oauthIdToken","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","UserCredentialImpl","operationType","_fromIdTokenResponse","providerIdForResponse","_updateTokensIfNecessary","MultiFactorError","_processCredentialSavingMfaContextIfNecessary","_fromErrorAndOperation","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","removeItem","BrowserLocalPersistence","poll","onStorageEvent","listeners","localCache","pollTimer","safariLocalStorageNotSynced","_iframeCannotSyncWebStorage","_isIframe","fallbackToPolling","forAllChangedKeys","_oldValue","notifyListeners","detachListener","stopPolling","storedValue","triggerListeners","startPolling","setInterval","StorageEvent","clearInterval","attachListener","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","Receiver","eventTarget","handlersMap","receivers","isListeningto","messageEvent","eventId","eventType","handlers","ports","postMessage","fulfilled","_allSettled","_subscribe","eventHandler","_unsubscribe","_generateEventId","Sender","removeMessageHandler","messageChannel","port1","onMessage","timeout","MessageChannel","completionTimer","ackTimer","port2","finally","_window","_isWorker","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","toPromise","getObjectStore","isReadWrite","_openDatabase","keyPath","_deleteDatabase","_putObject","_deleteObject","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","op","numAttempts","_openDb","initializeReceiver","initializeSender","_origin","keyProcessed","_poll","_data","serviceWorker","_getActiveServiceWorker","results","_send","_getServiceWorkerController","write","_withPendingWrite","_withRetries","notifyServiceWorker","getObject","getAllRequest","getAll","keysInResult","fbase_key","localKey","indexedDBLocalPersistence","_withDefaultResolver","resolverOverride","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_signInWithCredential","_reauth","parsed","_forOperation","_reauthenticate","_link","_link$1","AbstractPopupRedirectOperation","pendingPromise","eventManager","onExecution","registerConsumer","urlResponse","getIdpTask","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","authWindow","pollId","currentPopupAction","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","isSupported","pollUserCancellation","closed","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","pendingRedirectKey","resolverPersistence","hasPendingRedirect","_getAndClearPendingRedirectStatus","onAuthEvent","_redirectUserForId","signInWithRedirect","_assertInstanceOf","resolverInternal","_setPendingRedirectStatus","_openRedirect","_signInWithRedirect","_getRedirectResult","resolverExtern","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","onEvent","hasEventBeenHandled","consumer","isNullRedirectEvent","isRedirectEvent","eventIdMatches","eventUid","IP_ADDRESS_REGEX","HTTP_REGEX","_validateOrigin","authorizedDomains","_getProjectConfig","domain","matchDomain","expected","currentUrl","ceUrl","escapedDomainPattern","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","hint","CP","loadGapi","loadGapiIframe","gapi","iframes","ontimeout","Iframe","cbName","cachedGApiLoader","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","EID_FROM_APIHOST","getIframeUrl","eid","fw","_openIframe","_loadGapi","where","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","dontclear","iframe","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","AuthPopup","_open","availHeight","availWidth","scrollbars","optionsString","standalone","_isIOSStandalone","initMouseEvent","openAsNewWindowIOS","newWin","WIDGET_PATH","EMULATOR_WIDGET_PATH","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","authType","redirectUrl","additionalParams","isEmpty","tid","paramsDict","appCheckTokenFragment","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","eventManagers","originValidationPromises","_setWindowLocation","initAndGetManager","iframeEvent","authEvent","AuthInterop","internalListeners","getUid","assertAuthConfigured","addAuthTokenListener","updateProactiveRefresh","removeAuthTokenListener","authIdTokenMaxAge","lastPostedIdToken","getAuth","initializeAuth","authTokenSyncUrl","mintCookie","idTokenResult","idTokenAge","Authorization","authEmulatorHost","authInstance","hierarchy","_initializeAuthInstance","_instanceIdentifier","_instance","getVersionForPlatform","api","init","defaultAttributes","expires","escape","stringifiedAttributes","attributeName","cookies","jar","found","withAttributes","withConverter","commonjsGlobal","goog","aa","ca","da","ea","fa","q","ha","ac","sa","ba","ka","ma","na","oa","pa","qa","za","Da","va","wa","xa","ya","Aa","Ba","Ca","Ea","Fa","screenY","screenX","srcElement","fromElement","toElement","Ga","returnValue","Ha","Ia","Ja","la","ia","Ka","Na","Pa","Qa","Ra","Sa","Ua","Ta","Va","Wa","Ya","Za","$a","O","ab","bb","eb","fb","gb","detachEvent","J","ib","jb","lb","mb","ob","pb","qb","rb","sb","tb","vb","ub","wb","xb","ga","yb","zb","Ab","Bb","Cb","Db","Fb","Gb","Jb","Lb","Mb","Nb","Ob","Pb","STAT_EVENT","stat","F","Qb","Rb","Sb","NO_ERROR","Eb","TIMEOUT","Ib","Tb","Kb","$b","Ub","Vb","Wb","Xb","OPEN","Hb","Yb","Zb","bc","W","U","cc","G","Y","M","K","dc","ec","gc","hc","ic","jc","kc","lc","nb","oc","rc","uc","qc","vc","pc","wc","nc","sc","abort","xc","yc","zc","Ac","Bc","ra","La","Ma","getResponseHeader","Cc","Dc","Ec","Fc","Gc","Hc","Kc","Jc","Ic","ja","mc","TextDecoder","decode","stream","getAllResponseHeaders","Oa","tc","Lc","Nc","Oc","Pc","Qc","Rc","$c","Xc","Sc","Yc","decodeURI","encodeURI","Zc","Tc","Uc","Vc","Wc","Mc","ad","cd","dd","PerformanceNavigationTiming","getEntriesByType","nextHopProtocol","ed","fd","hd","kd","onabort","ld","md","nd","responseType","responseText","statusText","qd","Xa","pd","od","credentials","Request","arrayBuffer","ReadableStream","getReader","Uint8Array","rd","sd","td","ud","vd","yd","zd","Ad","wd","mozResponseArrayBuffer","Bd","Cd","Dd","internalChannelParams","Ed","xmlHttpFactory","supportsCrossDomainXhr","concurrentRequestLimit","fastHandshake","encodeInitMessageHeaders","forceLongPolling","detectBufferingProxy","longPollingTimeout","Fd","Gd","sendBeacon","Image","Hd","Ld","Kd","Jd","Md","Id","jd","Nd","Od","Q","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","initMessageHeaders","messageContentType","sendRawJson","httpSessionIdParam","Pd","__headers__","statusCode","__status__","__sm__","Qd","Sd","FormData","withCredentials","xd","kb","__data__","Td","Ud","Wd","Xd","X","Zd","$d","ae","Yd","be","LN2","and","or","xor","createWebChannel","HTTP_ERROR","COMPLETE","EventType","CLOSE","MESSAGE","listen","listenOnce","getLastError","getLastErrorCode","getStatus","getResponseJson","getResponseText","setWithCredentials","digest","multiply","modulo","compare","toNumber","getBits","fromNumber","fromString","Vd","ErrorCode","Stat","FetchXmlHttpFactory","WebChannel","XhrIo","Md5","Integer","User$1","isAuthenticated","toKey","isEqual","User","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","__PRIVATE_getLogLevel","__PRIVATE_logDebug","__PRIVATE_argToString","__PRIVATE_logError","__PRIVATE_logWarn","fail","__PRIVATE_hardAssert","__PRIVATE_debugCast","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","UNAVAILABLE","DATA_LOSS","FirestoreError","__PRIVATE_Deferred","__PRIVATE_OAuthToken","__PRIVATE_EmptyAuthCredentialsProvider","invalidateToken","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","changeListener","__PRIVATE_FirebaseAuthCredentialsProvider","__PRIVATE_guardedChangeListener","__PRIVATE_awaitNextToken","__PRIVATE_registerAuth","__PRIVATE_FirstPartyToken","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","__PRIVATE_FirebaseAppCheckTokenProvider","appCheck","onTokenChanged","__PRIVATE_registerAppCheck","addTokenListener","removeTokenListener","__PRIVATE_randomBytes","crypto","msCrypto","getRandomValues","__PRIVATE_AutoId","__PRIVATE_primitiveComparator","__PRIVATE_arrayEquals","every","Timestamp","nanoseconds","fromMillis","toDate","toMillis","_compareTo","padStart","SnapshotVersion","compareTo","toMicroseconds","toTimestamp","BasePath","segments","comparator","popFirst","popLast","firstSegment","lastSegment","isPrefixOf","isImmediateParentOf","ResourcePath","canonicalString","FieldPath$1","isValidIdentifier","isKeyField","__PRIVATE_addCurrentSegment","DocumentKey","emptyPath","collectionGroup","hasCollectionId","getCollectionGroup","getCollectionPath","__PRIVATE_newIndexOffsetFromDocument","IndexOffset","readTime","documentKey","largestBatchId","empty","__PRIVATE_indexOffsetComparator","PersistenceTransaction","onCommittedListeners","addOnCommittedListener","raiseOnCommittedEvent","__PRIVATE_ignoreIfPrimaryLeaseLoss","PersistencePromise","nextCallback","catchCallback","isDone","callbackAttached","wrapFailure","wrapSuccess","wrapUserFunction","waitFor","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_ListenSequence","sequenceNumberHandler","oe","writeSequenceNumber","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","__PRIVATE_objectSize","SortedMap","LLRBNode","EMPTY","insert","BLACK","minKey","maxKey","inorderTraversal","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","isReverse","nodeStack","getNext","hasNext","peek","RED","fixUp","removeMin","isRed","moveRedLeft","rotateRight","moveRedRight","rotateLeft","colorFlip","checkMaxDepth","check","SortedSet","forEachInRange","forEachWhile","firstAfterOrEqual","SortedSetIterator","unionWith","iter","FieldMask","fields","covers","__PRIVATE_Base64DecodeError","ByteString","binaryString","toBase64","toUint8Array","approximateByteSize","EMPTY_BYTE_STRING","te","__PRIVATE_normalizeTimestamp","nanos","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","fromBase64String","fromUint8Array","__PRIVATE_isServerTimestamp","mapValue","__type__","stringValue","__PRIVATE_getPreviousValue","__previous_value__","__PRIVATE_getLocalWriteTime","__local_write_time__","timestampValue","DatabaseInfo","databaseId","persistenceKey","ssl","autoDetectLongPolling","longPollingOptions","useFetchStreams","DatabaseId","database","isDefaultDatabase","ne","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_valueEquals","booleanValue","bytesValue","referenceValue","geoPointValue","latitude","longitude","integerValue","doubleValue","arrayValue","__PRIVATE_arrayValueContains","__PRIVATE_valueCompare","__PRIVATE_compareTimestamps","canonicalId","__PRIVATE_canonifyValue","fromName","__PRIVATE_refValue","isInteger","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","ObjectValue","getFieldsMap","setAll","applyChanges","clone","__PRIVATE_extractFieldMask","MutableDocument","documentType","createTime","documentState","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","Bound","inclusive","__PRIVATE_boundCompareToDocument","__PRIVATE_boundEquals","OrderBy","__PRIVATE_orderByEquals","Filter","FieldFilter","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matchesComparison","isInequality","getFlattenedFilters","getFilters","getFirstInequalityField","CompositeFilter","filters","ce","__PRIVATE_compositeFilterIsConjunction","le","__PRIVATE_compositeFilterIsFlatConjunction","__PRIVATE_compositeFilterIsFlat","__PRIVATE_canonifyFilter","__PRIVATE_filterEquals","__PRIVATE_stringifyFilter","__PRIVATE_extractDocumentKeysFromArrayValue","nullValue","__PRIVATE_TargetImpl","orderBy","startAt","endAt","he","__PRIVATE_newTarget","__PRIVATE_canonifyTarget","__PRIVATE_targetEquals","__PRIVATE_targetIsDocumentTarget","isDocumentKey","__PRIVATE_QueryImpl","explicitOrderBy","limitType","Pe","Ie","__PRIVATE_newQueryForPath","__PRIVATE_queryMatchesAllDocuments","__PRIVATE_getFirstOrderByField","__PRIVATE_getInequalityFilterField","__PRIVATE_isCollectionGroupQuery","__PRIVATE_queryOrderBy","keyField","__PRIVATE_queryToTarget","__PRIVATE_queryWithAddedFilter","__PRIVATE_queryWithLimit","__PRIVATE_queryEquals","__PRIVATE_canonifyQuery","__PRIVATE_stringifyQuery","__PRIVATE_queryMatches","__PRIVATE_newQueryComparator","__PRIVATE_compareDocs","ObjectMap","mapKeyFn","equalsFn","inner","innerSize","ie","__PRIVATE_mutableDocumentMap","se","documentMap","__PRIVATE_convertOverlayedDocumentMapToDocumentMap","overlayedDocument","__PRIVATE_newOverlayMap","__PRIVATE_newDocumentKeyMap","__PRIVATE_newMutationMap","__PRIVATE_documentKeySet","__PRIVATE_toDouble","useProto3Json","__PRIVATE_toInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","isSafeInteger","TransformOperation","__PRIVATE_applyTransformOperationToLocalView","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","__PRIVATE_applyArrayUnionTransformOperation","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_applyArrayRemoveTransformOperation","__PRIVATE_computeTransformOperationBaseValue","asNumber","Te","serializer","__PRIVATE_applyTransformOperationToRemoteDocument","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_coercedFieldValuesArray","MutationResult","transformResults","Precondition","updateTime","exists","isNone","__PRIVATE_preconditionIsValidForDocument","Mutation","__PRIVATE_calculateOverlayMutation","__PRIVATE_DeleteMutation","none","__PRIVATE_SetMutation","__PRIVATE_PatchMutation","__PRIVATE_mutationApplyToRemoteDocument","__PRIVATE_serverTransformResults","fieldTransforms","precondition","__PRIVATE_getPatch","__PRIVATE_mutationApplyToLocalView","__PRIVATE_localTransformResults","fieldMask","__PRIVATE_mutationExtractBaseValue","__PRIVATE_mutationEquals","__PRIVATE_fieldTransformEquals","getFieldMask","__PRIVATE_VerifyMutation","MutationBatch","batchId","localWriteTime","baseMutations","applyToRemoteDocument","mutationResults","applyToLocalView","applyToLocalDocumentSet","mutatedFields","MutationBatchResult","batch","commitVersion","docVersions","getKey","ExistenceFilter","unchangedNames","ue","__PRIVATE_mapCodeFromRpcCode","__PRIVATE_TestingHooks","onExistenceFilterMismatchCallbacks","onExistenceFilterMismatch","notifyOnExistenceFilterMismatch","__PRIVATE_getMd5HashValue","TextEncoder","__PRIVATE_get64BitUints","DataView","getUint32","BloomFilter","bitmap","padding","hashCount","__PRIVATE_BloomFilterError","de","Ae","Re","Ve","mightContain","me","RemoteEvent","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","TargetChange","createSynthesizedTargetChangeForCurrentChange","resumeToken","addedDocuments","modifiedDocuments","removedDocuments","__PRIVATE_DocumentWatchChange","fe","removedTargetIds","ge","__PRIVATE_ExistenceFilterChange","pe","__PRIVATE_WatchTargetChange","targetIds","__PRIVATE_TargetState","ye","we","__PRIVATE_snapshotChangesMap","Se","De","ve","Ce","Fe","Me","xe","Oe","Ne","Be","Le","ke","__PRIVATE_WatchChangeAggregator","qe","Qe","Ke","$e","__PRIVATE_documentTargetMap","Ue","We","Ge","ze","je","forEachTarget","He","Je","removeTarget","Ye","Ze","Xe","newNoDocument","et","tt","localCacheCount","existenceFilterCount","bloomFilter","applied","bitmapLength","bits","__PRIVATE_bloomFilterMightContain","getRemoteKeysForTarget","st","ot","purpose","_t","asc","in","JsonProtoSerializer","__PRIVATE_toInt32Proto","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","fromTimestamp","__PRIVATE_toResourceName","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_toName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_toQueryPath","__PRIVATE_getEncodedDatabaseId","__PRIVATE_toMutationDocument","__PRIVATE_toDocumentsTarget","documents","__PRIVATE_toQueryTarget","structuredQuery","collectionId","allDescendants","__PRIVATE_toFilter","__PRIVATE_toFieldPathReference","__PRIVATE_toDirection","before","__PRIVATE_convertQueryTargetToQuery","__PRIVATE_fromQueryPath","__PRIVATE_fromFilter","__PRIVATE_fromFieldPathReference","__PRIVATE_newQuery","unaryFilter","fieldFilter","compositeFilter","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","fieldPath","fromServerFormat","__PRIVATE_toDocumentMask","fieldPaths","TargetData","sequenceNumber","lastLimboFreeSnapshotVersion","expectedCount","withSequenceNumber","withResumeToken","withExpectedCount","withLastLimboFreeSnapshotVersion","__PRIVATE_LocalSerializer","__PRIVATE_fromBundledQuery","__PRIVATE_MemoryIndexManager","sn","__PRIVATE_MemoryCollectionParentIndex","addToCollectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getNextCollectionGroupToUpdate","getMinOffset","getMinOffsetFromCollectionGroup","updateCollectionGroup","updateIndexEntries","__PRIVATE_TargetIdGenerator","Mn","RemoteDocumentChangeBuffer","changes","changesApplied","addEntry","assertNotApplied","removeEntry","newInvalidDocument","getEntry","getFromCache","getAllFromCache","OverlayedDocument","LocalDocumentsView","remoteDocumentCache","mutationQueue","documentOverlayCache","indexManager","getDocument","getOverlay","getDocuments","getLocalViewOfDocuments","populateOverlays","computeViews","getOverlayedDocuments","getOverlays","recalculateAndSaveOverlays","getAllMutationBatchesAffectingDocumentKeys","saveOverlays","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingQuery","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","getNextDocuments","getAllFromCollectionGroup","getOverlaysForCollectionGroup","getOverlaysForCollection","__PRIVATE_MemoryBundleCache","ar","ur","getBundleMetadata","saveBundleMetadata","getNamedQuery","saveNamedQuery","bundledQuery","__PRIVATE_MemoryDocumentOverlayCache","overlays","cr","ht","removeOverlaysForBatchId","__PRIVATE_ReferenceSet","lr","__PRIVATE_DocReference","hr","Pr","Ir","addReference","Tr","removeReference","Er","dr","Ar","Rr","Vr","containsKey","mr","__PRIVATE_MemoryMutationQueue","referenceDelegate","gr","pr","checkEmpty","addMutationBatch","lookupMutationBatch","yr","getNextMutationBatchAfterBatchId","wr","getHighestUnacknowledgedBatchId","getAllMutationBatches","getAllMutationBatchesAffectingDocumentKey","POSITIVE_INFINITY","Sr","getAllMutationBatchesAffectingQuery","removeMutationBatch","br","markPotentiallyOrphaned","Cn","performConsistencyCheck","__PRIVATE_MemoryRemoteDocumentCacheImpl","Dr","docs","setIndexManager","vr","newChangeBuffer","__PRIVATE_MemoryRemoteDocumentChangeBuffer","getSize","sr","__PRIVATE_MemoryTargetCache","Cr","lastRemoteSnapshotVersion","highestTargetId","Fr","Mr","targetCount","Or","xn","getLastRemoteSnapshotVersion","getHighestSequenceNumber","allocateTargetId","setTargetsMetadata","Ln","addTargetData","updateTargetData","removeTargetData","removeTargets","removeMatchingKeysForTargetId","getTargetCount","getTargetData","addMatchingKeys","removeMatchingKeys","getMatchingKeysForTargetId","__PRIVATE_MemoryPersistence","Nr","Br","Lr","kr","qr","Qr","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","getTargetCache","getRemoteDocumentCache","getBundleCache","runTransaction","__PRIVATE_MemoryTransaction","Kr","$r","Ur","currentSequenceNumber","__PRIVATE_MemoryEagerDelegate","Wr","Gr","jr","Hr","updateLimboDocument","__PRIVATE_LocalViewChanges","fromCache","Li","ki","docChanges","__PRIVATE_QueryEngine","Qi","Ki","$i","Ui","Wi","Gi","zi","ji","__PRIVATE_newIndexOffsetSuccessorFromReadTime","__PRIVATE_LocalStoreImpl","Hi","Ji","Yi","Zi","Xi","es","localDocuments","collectGarbage","collect","__PRIVATE_localStoreHandleUserChange","removedBatchIds","addedBatchIds","__PRIVATE_localStoreGetLastRemoteSnapshotVersion","__PRIVATE_localStoreApplyRemoteEventToLocalCache","trackRemovals","ns","rs","__PRIVATE_populateDocumentChangeBuffer","__PRIVATE_localStoreGetNextMutationBatch","__PRIVATE_localStoreReleaseTarget","__PRIVATE_localStoreExecuteQuery","__PRIVATE_setMaxReadTime","__PRIVATE_queryCollectionGroup","__PRIVATE_LocalClientState","activeTargetIds","hs","Ps","ls","updateTimeMs","__PRIVATE_MemorySharedClientState","Hs","Js","onlineStateHandler","addPendingMutation","updateMutationState","addLocalQueryTarget","updateQueryState","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","getAllActiveQueryTargets","isActiveQueryTarget","handleUserChange","setOnlineState","notifyBundleLoaded","__PRIVATE_NoopConnectivityMonitor","Ys","__PRIVATE_BrowserConnectivityMonitor","Zs","Xs","eo","no","ro","io","__PRIVATE_generateUniqueDebugId","BatchGetDocuments","Commit","RunQuery","RunAggregationQuery","__PRIVATE_StreamBridge","so","oo","_o","ao","uo","co","lo","ho","Po","Io","__PRIVATE_WebChannelConnection","databaseInfo","To","Eo","Ao","Ro","Vo","mo","fo","po","yo","wo","forwardChannelRequestTimeoutMs","timeoutSeconds","__PRIVATE_unguardedEventListen","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","ii","So","bo","Do","vo","Co","Fo","Mo","xo","Oo","enqueueAfterDelay","No","skipDelay","__PRIVATE_PersistentStream","Bo","Lo","connection","authCredentialsProvider","appCheckCredentialsProvider","ko","qo","Qo","Ko","$o","Uo","Wo","Go","zo","jo","Ho","Jo","Yo","Zo","Xo","e_","t_","n_","enqueueAndForget","__PRIVATE_PersistentListenStream","targetChange","targetChangeType","documentChange","newFoundDocument","documentDelete","documentRemove","__PRIVATE_fromWatchChange","r_","i_","addTarget","__PRIVATE_toListenRequestLabels","s_","__PRIVATE_PersistentWriteStream","o_","__","lastStreamToken","a_","streamToken","__PRIVATE_fromWriteResults","writeResults","commitTime","u_","c_","l_","writes","updateMask","updateTransforms","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","toMutation","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","h_","P_","terminate","__PRIVATE_OnlineStateTracker","asyncQueue","T_","E_","d_","A_","R_","V_","m_","f_","__PRIVATE_RemoteStoreImpl","localStore","datastore","remoteSyncer","g_","p_","y_","w_","S_","__PRIVATE_canUseNetwork","__PRIVATE_disableNetworkInternal","b_","__PRIVATE_enableNetworkInternal","__PRIVATE_remoteStoreListen","__PRIVATE_shouldStartWatchStream","__PRIVATE_startWatchStream","__PRIVATE_ensureWatchStream","__PRIVATE_sendWatchRequest","__PRIVATE_remoteStoreUnlisten","__PRIVATE_sendUnwatchRequest","D_","__PRIVATE_cleanUpWatchStreamState","__PRIVATE_onWatchStreamOpen","__PRIVATE_onWatchStreamClose","__PRIVATE_onWatchStreamChange","rejectListen","__PRIVATE_disableNetworkUntilRecovery","applyRemoteEvent","__PRIVATE_executeWithRecovery","__PRIVATE_fillWritePipeline","__PRIVATE_ensureWriteStream","__PRIVATE_canAddToWritePipeline","__PRIVATE_addToWritePipeline","__PRIVATE_shouldStartWriteStream","__PRIVATE_startWriteStream","__PRIVATE_onWriteStreamOpen","__PRIVATE_onWriteHandshakeComplete","__PRIVATE_onMutationResult","applySuccessfulWrite","__PRIVATE_onWriteStreamClose","__PRIVATE_isPermanentError","rejectFailedWrite","__PRIVATE_remoteStoreHandleCredentialChange","verifyOperationInProgress","handleCredentialChange","v_","stop","C_","DelayedOperation","targetTimeMs","removalCallback","timerHandle","handleDelayElapsed","__PRIVATE_wrapInUserErrorIfRecoverable","DocumentSet","keyedMap","sortedSet","__PRIVATE_DocumentChangeSet","F_","track","M_","ViewSnapshot","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","emptySet","__PRIVATE_QueryListenersInfo","x_","__PRIVATE_EventManagerImpl","queries","onlineState","O_","__PRIVATE_eventManagerListen","onListen","N_","B_","__PRIVATE_raiseSnapshotsInSyncEvent","__PRIVATE_eventManagerUnlisten","onUnlisten","__PRIVATE_eventManagerOnWatchChange","__PRIVATE_eventManagerOnWatchError","__PRIVATE_QueryListener","L_","k_","q_","includeMetadataChanges","Q_","K_","U_","W_","fromInitialDocuments","__PRIVATE_AddedLimboDocument","__PRIVATE_RemovedLimboDocument","__PRIVATE_View","X_","snapshot","__PRIVATE_QueryView","view","LimboResolution","__PRIVATE_SyncEngineImpl","remoteStore","sharedClientState","maxConcurrentLimboResolutions","On","isPrimaryClient","__PRIVATE_syncEngineListen","__PRIVATE_syncEngineApplyRemoteEvent","__PRIVATE_syncEngineGetRemoteKeysForTarget","__PRIVATE_syncEngineRejectListen","__PRIVATE_ensureWatchCallbacks","__PRIVATE_localStoreAllocateTarget","__PRIVATE_updateTrackedLimbos","__PRIVATE_initializeViewAndComputeSnapshot","__PRIVATE_syncEngineUnlisten","__PRIVATE_removeAndCleanupTarget","__PRIVATE_syncEngineWrite","__PRIVATE_syncEngineApplySuccessfulWrite","__PRIVATE_syncEngineRejectFailedWrite","__PRIVATE_syncEngineEnsureWriteCallbacks","__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore","__PRIVATE_syncEngineApplyOnlineStateChange","__PRIVATE_pumpEnqueuedLimboResolutions","__PRIVATE_localStoreAcknowledgeBatch","__PRIVATE_processUserCallback","__PRIVATE_triggerPendingWritesCallbacks","__PRIVATE_removeLimboTarget","__PRIVATE_trackLimboChange","qi","__PRIVATE_syncEngineHandleCredentialChange","MemoryOfflineComponentProvider","synchronizeTabs","createSharedClientState","createPersistence","createLocalStore","gcScheduler","createGarbageCollectionScheduler","indexBackfillerScheduler","createIndexBackfillerScheduler","__PRIVATE_newLocalStore","initialUser","zr","OnlineComponentProvider","createDatastore","createRemoteStore","createEventManager","syncEngine","createSyncEngine","__PRIVATE_remoteStoreApplyPrimaryState","__PRIVATE_AsyncObserver","muted","FirestoreClient","authCredentialListener","appCheckCredentialListener","setCredentialChangeListener","setAppCheckTokenChangeListener","verifyNotTerminated","isShuttingDown","enterRestrictedMode","enqueueAndForgetEvenWhileRestricted","_onlineComponents","_offlineComponents","__PRIVATE_setOfflineComponentProvider","getConfiguration","__PRIVATE_setOnlineComponentProvider","_uninitializedComponentsProvider","_offline","__PRIVATE_canFallbackFromIndexedDbError","__PRIVATE_ensureOfflineComponents","__PRIVATE_ensureOnlineComponents","_online","__PRIVATE_getEventManager","__PRIVATE_cloneLongPollingOptions","__PRIVATE_validateNonEmptyArgument","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_valueDescription","__PRIVATE_cast","FirestoreSettingsImpl","ignoreUndefinedProperties","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","Firestore$1","_authCredentials","_appCheckCredentials","_databaseId","_app","_persistenceKey","_settings","_settingsFrozen","_terminated","_terminateTask","_setSettings","sessionIndex","iamToken","authTokenFactory","_getSettings","_freezeSettings","_terminate","Query","_query","firestore","DocumentReference","_path","CollectionReference","collection","__PRIVATE_AsyncQueueImpl","visibilityState","enqueue","eu","tu","nu","createAndSchedule","ru","su","ou","iu","_u","Firestore","_queue","_firestoreClient","__PRIVATE_configureFirestore","getFirestore","mockUserToken","connectFirestoreEmulator","ensureFirestoreConfigured","_offlineComponentProvider","_onlineComponentProvider","_offlineKind","Bytes","_byteString","FieldPath","_internalPath","FieldValue","_methodName","GeoPoint","_lat","_long","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_ParseContextImpl","au","uu","cu","lu","hu","Pu","Iu","Tu","Eu","__PRIVATE_createError","du","Au","__PRIVATE_UserDataReader","Ru","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_parseObject","__PRIVATE_fieldPathFromArgument$1","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_parseData","__PRIVATE_looksLikeJsonObject","fromDate","__PRIVATE_fieldPathFromDotSeparatedString","DocumentSnapshot$1","_firestore","_userDataWriter","_document","_converter","ref","QueryDocumentSnapshot$1","fromFirestore","convertValue","__PRIVATE_fieldPathFromArgument","AppliableConstraint","QueryConstraint","QueryCompositeFilterConstraint","QueryFieldFilterConstraint","_apply","_field","_op","_value","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_parseDocumentIdValue","__PRIVATE_parseQueryValue","_queryConstraints","_getOperator","_getQueryConstraints","QueryOrderByConstraint","_direction","__PRIVATE_validateOrderByAndInequalityMatch","AbstractUserDataWriter","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertObjectMap","convertDocumentKey","__PRIVATE_applyFirestoreDataConverter","toFirestore","SnapshotMetadata","DocumentSnapshot","_firestoreImpl","QueryDocumentSnapshot","serverTimestamps","QuerySnapshot","_snapshot","_cachedChanges","_cachedChangesIncludeMetadataChanges","newIndex","__PRIVATE_resultChangeType","getDoc","__PRIVATE_firestoreClientGetDocumentViaSnapshotListener","__PRIVATE_ExpUserDataWriter","__PRIVATE_convertToDocSnapshot","getDocs","__PRIVATE_validateHasExplicitOrderByForLimitToLast","__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener","executeWrite","__PRIVATE_getSyncEngine","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","_verifyNotCommitted","__PRIVATE_validateReference","__PRIVATE_parseUpdateVarargs","__PRIVATE_parseUpdateData","commit","AssertionError","assertDefined","FIRESTORE_STATE","INVITE_COLLECTION_ID","USER_COLLECTION_ID","WORKSPACE_COLLECTION_ID","strictEqual","WORKSPACE_ID_REGEXP","Entity","_dirty","workspaceId","checkDeleted","markDirty","maybeMarkDirty","setDoc","writeInBatch","afterCommit","deleteDoc","deleteInBatch","assert","UserError","UserDataError","AutomaticTagsMode","_displayName","_email","_photoURL","_automaticTagsMode","SHOW_BEFORE_CUSTOM","automaticTagsMode","userIds","_create","USER_DATA_CONVERTER","_enum","enumName","assertStrEnum","AUTH_STATE","authStateChangeListeners","loadOrCreate","getSessionCookie","login","logout","onAuthStateChange","csrfToken","Cookies","sameSite","secure","LONG_TYPE","UNSIGNED_LONG_TYPE","mapValues","FUNCTIONS_TYPE","errorCodeMap","FunctionsError","details","ContextProvider","authProvider","messagingProvider","appCheckProvider","messaging","permission","limitedUseAppCheckTokens","getLimitedUseToken","authToken","getAuthToken","messagingToken","getMessagingToken","getAppCheckToken","DEFAULT_REGION","FunctionsService","regionOrCustomDomain","emulatorOrigin","contextProvider","cancelAllRequests","deleteService","customDomain","region","_url","httpsCallable$1","functionsInstance","failAfterHandle","millis","failAfter","postJSON","bodyJSON","codeForHTTPStatus","description","errorJSON","_errorForResponse","responseData","callAtURL","getFunctions","connectFunctionsEmulator$1","connectFunctionsEmulator","httpsCallable","registerFunctions","LuxonError","InvalidDateTimeError","toMessage","InvalidIntervalError","InvalidDurationError","ConflictingSpecificationError","InvalidUnitError","unit","InvalidArgumentError","ZoneIsAbstractError","DATE_SHORT","DATE_MED","DATE_MED_WITH_WEEKDAY","weekday","DATE_FULL","DATE_HUGE","TIME_SIMPLE","hour","minute","TIME_WITH_SECONDS","TIME_WITH_SHORT_OFFSET","timeZoneName","TIME_WITH_LONG_OFFSET","TIME_24_SIMPLE","hourCycle","TIME_24_WITH_SECONDS","TIME_24_WITH_SHORT_OFFSET","TIME_24_WITH_LONG_OFFSET","DATETIME_SHORT","DATETIME_SHORT_WITH_SECONDS","DATETIME_MED","DATETIME_MED_WITH_SECONDS","DATETIME_MED_WITH_WEEKDAY","DATETIME_FULL","DATETIME_FULL_WITH_SECONDS","DATETIME_HUGE","DATETIME_HUGE_WITH_SECONDS","Zone","ianaName","isUniversal","offsetName","formatOffset","otherZone","singleton","SystemZone","Intl","DateTimeFormat","resolvedOptions","timeZone","parseZoneInfo","getTimezoneOffset","dtfCache","typeToPos","era","ianaZoneCache","IANAZone","isValidZone","zone","zoneName","dtf","hour12","adOrBc","formatToParts","filled","isUndefined","partsOffset","fMonth","fDay","fYear","fadOrBc","fHour","fMinute","fSecond","hackyOffset","asTS","over","objToLocalTS","millisecond","intlLFCache","intlDTCache","getCachedDTF","locString","intlNumCache","intlRelCache","sysLocaleCache","listStuff","loc","defaultOK","englishFn","intlFn","listingMode","PolyNumberFormatter","intl","forceSimple","padTo","otherOpts","intlOpts","useGrouping","minimumIntegerDigits","inf","NumberFormat","getCachedINF","fixed","roundTo","PolyDateFormatter","dt","originalZone","gmtOffset","offsetZ","setZone","plus","toJSDate","PolyRelFormatter","isEnglish","hasRelative","rtf","cacheKeyOpts","RelativeTimeFormat","getCachedRTF","numeric","narrow","units","quarters","weeks","lastable","isDay","isInPast","fmtValue","singular","lilUnits","fmtUnit","English.formatRelativeTime","Locale","numberingSystem","outputCalendar","defaultToEN","specifiedLocale","Settings","defaultLocale","localeR","numberingSystemR","defaultNumberingSystem","outputCalendarR","defaultOutputCalendar","numbering","parsedLocale","parsedNumberingSystem","parsedOutputCalendar","localeStr","xIndex","uIndex","selectedStr","smaller","parseLocaleString","intlConfigString","weekdaysCache","monthsCache","meridiemCache","eraCache","fastNumbersCached","fastNumbers","isActuallyEn","hasNoWeirdness","alts","redefaultToEN","redefaultToSystem","English.months","formatStr","ms","DateTime","utc","mapMonths","extract","English.weekdays","mapWeekdays","meridiems","English.meridiems","eras","English.eras","matching","dtFormatter","numberFormatter","relFormatter","listFormatter","ListFormat","getCachedLF","other","FixedOffsetZone","utcInstance","signedOffset","InvalidZone","normalizeZone","defaultZone","lowered","parseSpecifier","isNumber","throwOnInvalid","twoDigitCutoffYear","cutoffYear","resetCache","bestBy","by","best","pair","integerBetween","padded","parseInteger","parseFloating","parseMillis","fraction","towardZero","factor","trunc","isLeapYear","daysInYear","daysInMonth","modMonth","floorMod","UTC","setUTCFullYear","weeksInWeekYear","weekYear","p1","p2","untruncateYear","offsetFormat","modified","offHourStr","offMinuteStr","offHour","offMin","numericValue","normalizeObject","normalizer","normalized","sign","RangeError","pick","monthsLong","monthsShort","monthsNarrow","weekdaysLong","weekdaysNarrow","erasLong","erasShort","erasNarrow","stringifyTokens","splits","tokenToString","macroTokenToFormatOpts","Formats.DATE_SHORT","DD","Formats.DATE_MED","DDD","Formats.DATE_FULL","DDDD","Formats.DATE_HUGE","Formats.TIME_SIMPLE","Formats.TIME_WITH_SECONDS","ttt","Formats.TIME_WITH_SHORT_OFFSET","tttt","Formats.TIME_WITH_LONG_OFFSET","Formats.TIME_24_SIMPLE","TT","Formats.TIME_24_WITH_SECONDS","TTT","Formats.TIME_24_WITH_SHORT_OFFSET","TTTT","Formats.TIME_24_WITH_LONG_OFFSET","Formats.DATETIME_SHORT","ff","Formats.DATETIME_MED","fff","Formats.DATETIME_FULL","ffff","Formats.DATETIME_HUGE","Formats.DATETIME_SHORT_WITH_SECONDS","FF","Formats.DATETIME_MED_WITH_SECONDS","FFF","Formats.DATETIME_FULL_WITH_SECONDS","FFFF","Formats.DATETIME_HUGE_WITH_SECONDS","Formatter","currentFull","bracketed","formatOpts","systemLoc","formatWithSystemDefault","formatDateTime","formatDateTimeParts","formatInterval","formatRange","formatDateTimeFromString","knownEnglish","useDateTimeFormatter","isOffsetFixed","allowZ","meridiem","English.meridiemForDateTime","English.monthForDateTime","English.weekdayForDateTime","maybeMacro","English.eraForDateTime","parseFormat","weekNumber","ordinal","quarter","formatDurationFromString","dur","tokenToField","realTokens","collapsed","shiftTo","lildur","mapped","Invalid","explanation","ianaRegex","combineRegexes","regexes","full","combineExtractors","extractors","mergedVals","mergedZone","cursor","ex","regex","extractor","simpleParse","offsetRegex","isoTimeBaseRegex","isoTimeRegex","isoTimeExtensionRegex","extractISOWeekData","extractISOOrdinalData","sqlTimeRegex","sqlTimeExtensionRegex","int","fallback","extractISOTime","extractISOOffset","local","fullOffset","extractIANAZone","isoTimeOnly","isoDuration","extractISODuration","monthStr","weekStr","dayStr","hourStr","minuteStr","secondStr","millisecondsStr","hasNegativePrefix","negativeSeconds","maybeNegate","force","obsOffsets","GMT","EDT","EST","CDT","CST","MDT","MST","PDT","PST","fromStrings","weekdayStr","English.monthsShort","English.weekdaysLong","English.weekdaysShort","rfc2822","extractRFC2822","obsOffset","milOffset","rfc1123","rfc850","ascii","extractRFC1123Or850","extractASCII","isoYmdWithTimeExtensionRegex","isoWeekWithTimeExtensionRegex","isoOrdinalWithTimeExtensionRegex","isoTimeCombinedRegex","extractISOYmdTimeAndOffset","extractISOWeekTimeAndOffset","extractISOOrdinalDateAndTime","extractISOTimeAndOffset","extractISOTimeOnly","sqlYmdWithTimeExtensionRegex","sqlTimeCombinedRegex","extractISOTimeOffsetAndIANAZone","lowOrderMatrix","casualMatrix","daysInYearAccurate","daysInMonthAccurate","accurateMatrix","orderedUnits","reverseUnits","conf","conversionAccuracy","matrix","Duration","convert","fromMap","fromUnit","toMap","toUnit","conv","added","antiTrunc","accurate","isLuxonDuration","fromObject","normalizeUnit","durationLike","isDuration","parseISODuration","parseISOTimeOnly","toFormat","fmtOpts","toHuman","unitDisplay","listStyle","toObject","toISO","toISOTime","suppressMilliseconds","suppressSeconds","includePrefix","fromDurationLike","minus","mapUnits","reconfigure","vals","normalizeValues","rescale","newVals","removeZeroes","shiftToAll","built","accumulated","lastUnit","own","ak","down","negated","invalidReason","invalidExplanation","v1","v2","INVALID","Interval","isLuxonInterval","builtStart","friendlyDateTime","builtEnd","validateError","validateStartEnd","fromDateTimes","startIsValid","endIsValid","fromISO","toDuration","startOf","hasSame","isAfter","dateTime","isBefore","splitAt","dateTimes","sorted","splitBy","divideEqually","numberOfParts","overlaps","abutsStart","abutsEnd","engulfs","intersection","union","intervals","final","sofar","ends","difference","toLocaleString","toISODate","dateFormat","separator","mapEndpoints","mapFn","Info","locObj","relative","dayDiff","earlier","later","utcDayStart","toUTC","keepLocalTime","highWater","lowestOrder","differs","differ","highOrderDiffs","remainingMillis","lowerOrderUnits","numberingSystems","arab","arabext","bali","beng","deva","fullwide","gujr","hanidec","khmr","knda","laoo","limb","mlym","mong","mymr","orya","tamldec","telu","thai","tibt","latn","numberingSystemsUTF16","hanidecChars","digitRegex","MISSING_FTP","intUnit","deser","parseDigits","spaceOrNBSP","spaceOrNBSPRegExp","fixListRegex","stripInsensitivities","oneOf","simple","partTypeStyleToTokenVal","short","long","dayperiod","dayPeriod","dummyDateTimeCache","expandMacroTokens","formatOptsToTokens","maybeExpandMacroToken","explainFromTokens","one","two","three","four","six","oneOrTwo","oneToThree","oneToSix","oneToNine","twoToFour","fourToSix","unitate","unitForToken","disqualifyingUnit","regexString","buildRegex","rawMatches","matchIndex","specificOffset","toField","dateTimeFromMatches","isSpace","tokenForPart","nonLeapLadder","leapLadder","unitOutOfRange","getUTCFullYear","js","getUTCDay","computeOrdinal","uncomputeOrdinal","table","month0","gregorianToWeek","gregObj","weekToGregorian","weekData","weekdayOfJan4","yearInDays","gregorianToOrdinal","gregData","ordinalToGregorian","ordinalData","hasInvalidGregorianData","validYear","validMonth","validDay","hasInvalidTimeData","validHour","validMinute","validSecond","validMillisecond","MAX_DATE","unsupportedZone","possiblyCachedWeekData","fixOffset","localTS","tz","utcGuess","o2","o3","tsToObj","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","objToTS","adjustTime","oPre","millisToAdd","parseDataToDateTime","parsedZone","interpretationZone","toTechFormat","longFormat","includeOffset","extendedZone","defaultUnitValues","defaultWeekUnitValues","defaultOrdinalUnitValues","orderedWeekUnits","orderedOrdinalUnits","weeknumber","weeksnumber","weeknumbers","weekyear","weekyears","quickDT","tsNow","offsetProvis","diffRelative","calendary","lastOpts","_zone","isLuxonDateTime","isDate","zoneToUse","containsOrdinal","containsGregorYear","containsGregorMD","containsGregor","definiteWeekDef","useWeekData","defaultValues","objNow","foundFirst","higherOrderInvalid","validWeek","validWeekday","hasInvalidWeekData","validOrdinal","hasInvalidOrdinalData","gregorian","tsFinal","offsetFinal","parseISODate","preprocessRFC2822","parseRFC2822Date","parseHTTPDate","localeToUse","fromOpts","parseFromTokens","fromFormat","parseSQL","localeOpts","tokenList","monthShort","monthLong","weekdayShort","weekdayLong","offsetNameShort","offsetNameLong","isInDST","isInLeapYear","resolvedLocaleOptions","toLocal","keepCalendarTime","newTS","offsetGuess","asObj","setLocale","settingWeekStuff","mixed","normalizedUnit","endOf","toLocaleParts","toISOWeekDate","toRFC2822","toHTTP","toSQLDate","toSQLTime","includeZone","includeOffsetSpace","toSQL","toSeconds","toUnixInteger","toBSON","includeConfig","otherDateTime","durOpts","otherIsLater","diffed","diffNow","until","inputMs","adjustedToZone","toRelative","toRelativeCalendar","isDateTime","fromFormatExplain","Formats.DATE_MED_WITH_WEEKDAY","Formats.DATETIME_MED_WITH_WEEKDAY","dateTimeish","fromJSDate","Batch","afterCommitFns","writeBatch","InviteError","InviteDataError","Invite","expiry","_expiry","workspaceID","INVITE_DATA_CONVERTER","invites","expired","invite","fromData","FUNCTIONS_STATE","functions","_inviteToWorkspace","_acceptInvite","_rejectInvite","workspace","invitesData","addInvites","expirySecs","inviteId","DEFAULT_HOST","StorageError","status_","prependCode","_baseMessage","_codeEquals","StorageErrorCode","invalidArgument","appDeleted","APP_DELETED","Location","bucket","path_","isRoot","fullServerUrl","bucketOnlyServerUrl","bucketString","bucketLocation","makeFromUrl","INVALID_DEFAULT_BUCKET","bucketDomain","gsRegex","httpModify","firebaseStorageHost","indices","postModify","captures","bucketValue","INVALID_URL","invalidUrl","FailRequest","promise_","getPromise","_appDelete","validateNumber","argument","minValue","maxValue","NetworkRequest","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","timeout_","progressCallback_","connectionFactory_","retry","pendingConnection_","backoffId_","canceled_","appDelete_","resolve_","reject_","start_","doTheRequest","backoffCallback","RequestEndStatus","progressListener","progressEvent","loaded","lengthComputable","addUploadProgressListener","removeUploadProgressListener","hitServer","getErrorCode","additionalRetryCodes","isFiveHundredCode","isExtraRetryCode","isAdditionalRetryCode","isRetryStatusCode","wasCanceled","ABORT","successCode","backoffDone","requestWentThrough","wasSuccessCode","getResponse","isJustDef","CANCELED","RETRY_LIMIT_EXCEEDED","doRequest","backoffCompleteCb","waitSeconds","retryTimeoutId","globalTimeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","callWithDelay","responseHandler","clearGlobalTimeout","waitMillis","stopped","wasTimeout","appDelete","makeRequest","requestInfo","requestFactory","firebaseVersion","queryPart","makeQueryString","urlParams","addGmpidHeader_","addAuthHeader_","addVersionHeader_","addAppCheckHeader_","successCodes","progressCallback","Reference","_service","_location","_newRef","lastComponent","newPath","_throwIfRoot","INVALID_ROOT_OPERATION","invalidRootOperation","extractBucket","makeFromBucketSpec","FirebaseStorageImpl","_authProvider","_appCheckProvider","_firebaseVersion","_bucket","_host","_protocol","_appId","_maxOperationRetryTime","_maxUploadRetryTime","_requests","maxUploadRetryTime","maxOperationRetryTime","_overrideAuthToken","tokenData","_makeStorageReference","_makeRequest","_getAuthToken","STORAGE_TYPE","getStorage","bucketUrl","storageInstance","connectStorageEmulator$1","connectStorageEmulator","STORAGE_STATE","firebaseConfig","storageBucket","messagingSenderId","measurementId","FIREBASE_STATE","assertInitialized","BaseElement","listenWhileConnected","signal","AbortController","SetTitleEvent","SET_TITLE","CloseDialogEvent","CLOSE_DIALOG","ROUTES","acceptInvite","show","rejectInvite","BASE_TITLE","App","changeTitle","CANCEL_ACTION","Dialog","preventAutomaticClose","beforeClose","afterClose","doClose","maybeClose","maybeCancel","dialog","showInline","offsetX","offsetY","DialogActionButton","DialogCloseButton","Header","go","IconButton","buttonAriaLabel","LoginView","onBeforeEnter","URLSearchParams"],"mappings":"AA0CO,SAASA,EAAOC,EAAGC,GACtB,IAAIC,EAAI,CAAA,EACR,IAAK,IAAIC,KAAKH,EAAOI,OAAOC,UAAUC,eAAeC,KAAKP,EAAGG,IAAMF,EAAEO,QAAQL,GAAK,IAC9ED,EAAEC,GAAKH,EAAEG,IACb,GAAS,MAALH,GAAqD,mBAAjCI,OAAOK,sBACtB,KAAIC,EAAI,EAAb,IAAgBP,EAAIC,OAAOK,sBAAsBT,GAAIU,EAAIP,EAAEQ,OAAQD,IAC3DT,EAAEO,QAAQL,EAAEO,IAAM,GAAKN,OAAOC,UAAUO,qBAAqBL,KAAKP,EAAGG,EAAEO,MACvER,EAAEC,EAAEO,IAAMV,EAAEG,EAAEO,IAF4B,CAItD,OAAOR,CACX,CAEO,SAASW,EAAWC,EAAYC,EAAQC,EAAKC,GAChD,IAA2HC,EAAvHC,EAAIC,UAAUT,OAAQU,EAAIF,EAAI,EAAIJ,EAAkB,OAATE,EAAgBA,EAAOb,OAAO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N,GAAc,UACtC,CAESlgO,SACR,OAAOS,CAAI;;;oCAGqBvQ,KAAKozM;;KAGtC,CAEOA,QACNJ,GAAWI,OACZ,GAxBUy+B,GAASvzO,EAAA,CADrBoS,EAAc,yBACFmhO","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,271]}